Terraform: how to pass multiple integers to JSON

Viewed 412

Say we have three three variables in JSON:

{
    name: "Someone",
    age: 30,
    code: 25
}

and I want to read this as a template in terraform and replace the integer values. For one variable, I could solve this by modifying the JSON into:

{
    name: "Someone",
    age: "${age}",
    code: 25
}

and then on my template, do this:

template = replace(file("file.json"), "\"$${age}\"", "$${age}")

but in this case, I have another variable called code which I have to update as well, is there any way to accomplish this? Thank you!

EDIT 1:

This is the JSON:
{
  name: "Someone",
  age: "${age}",
  code: "${code}"
}


This is the terraform:
data "template_file" "part_1" {
template = file("file.json")

vars = {
  age = var.age
  code= var.code
}
}

This works all fine, but I need the 'age' and 'count' on JSON as integer, not as strings. If I keep JSON like this:

{
  name: "Someone",
  age: ${age},
  code: ${code}
}

It gives me an inappropriate JSON format. That's why I add the replace to template, so I can remove the double quotes and place there an integer, but I can do this only once!

1 Answers

Try this:

template = "${replace( "${replace(file("file.json"), "\"$${age}\"", "$${age}")}" ), "\"$${code}\"", "$${code}" }"

Here I'm replacing value again after return first replacement. It works for me. If you have more number of variable then you have to use multiple replace. Hope it will be helpful

Related