Use Case
- Using JSON files as input variables and local variables .
- Using jsonencode from json template file with the for loop
Procedure
JSON input variable for all values , prepare files as below and execute :-
- main.tf file :-
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
}
- test.json file :-
{
"name": "testname",
"age": 100,
"city": "San Francisco"
}
-
- ran
terraform apply -var="json_input=test.json"
, that took values from json file and worked as expected .
- ran
>>>>>
If you want to use json file's input items in for loop, You can use it similar to below example :-
-
main.tf
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
}
- template.tpl file :-
{
"items": ${items_json}
}
- This time, inside the
vars
block, we use afor
loop to iterate over each item in thevar.items
list. In each iteration, we create a map with the key “name” and the value as the current item. This list of maps is then passed tojsonencode
to create a JSON array. terraform apply
Additional Information
- For additional assistance please contact HashiCorp Support.