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 :-
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
}
{
"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 .
>>>>>
If you want to use json file's input items in for loop, You can use it similar to below example :-
# 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
}
{
"items": ${items_json}
}
- This time, inside the
vars block, we use a for loop to iterate over each item in the var.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 to jsonencode to create a JSON array.
terraform apply
Additional Information