Introduction
This guide demonstrates two methods for using JSON data with Terraform. You can either use a static JSON file as an input variable or dynamically generate a JSON file from a list using a template and a for loop.
Procedure
Follow the steps for the method that best fits your use case.
Method 1: Use a JSON file as an input variable
This method is suitable when you have a complete JSON file that you want to use for variable values.
Create a
main.tffile that defines an input variable for the JSON file path and uses thejsondecodeandfilefunctions to parse its content.variable "json_input" { description = "Path to the JSON input file" type = string } locals { input_data = jsondecode(file(var.json_input)) } output "name" { value = local.input_data.name }Create a JSON file named
test.jsonwith the data you want to use.{ "name": "testname", "age": 100, "city": "San Francisco" }Run
terraform applyand pass the path to your JSON file using the-varflag.$ terraform apply -var="json_input=test.json"
Terraform will read the file, parse the JSON content, and use the values as defined.
Method 2: Generate a JSON file using a template and a for loop
This method is useful when you need to construct a JSON file dynamically from a Terraform list variable.
Create a
main.tffile. This configuration defines a list of strings, then uses thetemplate_filedata source with aforloop and thejsonencodefunction to create a JSON structure. Finally, it saves the result to a local file.# Define a list of items variable "items" { type = list(string) default = ["Rahul", "Test1", "Test2"] } # Render the template data "template_file" "items_template" { template = file("template.tpl") vars = { items_json = jsonencode([for item in var.items : { name = item }]) } } # Create a local file to save the generated JSON resource "local_file" "items_json" { filename = "items.json" content = data.template_file.items_template.rendered }Create a template file named
template.tpl.{ "items": ${items_json} }Run
terraform applyto generate theitems.jsonfile.$ terraform apply
This process iterates over the
var.itemslist, creates a JSON array of objects, and writes it to theitems.jsonfile.