Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform interpolation to json file when json requires value to be integer

Tags:

terraform

Trying to work out if this is possible or not. Trawled terraform docs to no avail (not much surprise there).

Take the below extremely slim line example.

[
  {
    "cpu": "${var.master_container_cpu}",
  }
]

Adjoined to this tf parameter when invoking aws_ecs_task_definition resource;

container_definitions = "${file("task-definitions/example.json")}"

Will result in the following error;

Error: aws_ecs_task_definition.example-task: ECS Task Definition container_definitions is invalid: Error decoding JSON: json: cannot unmarshal string into Go struct field ContainerDefinition.Cpu of type int64

any help more than welcome :)

like image 495
David Avatar asked Apr 25 '18 11:04

David


People also ask

What format is used for interpolation in Terraform?

Embedded within strings in Terraform, whether you're using the Terraform syntax or JSON syntax, you can interpolate other values. These interpolations are wrapped in ${} , such as ${var. foo} .

How do Terraform interpolate variables?

Use the var. prefix followed by the variable name. For example, ${var. foo} will interpolate the foo variable value.

What file extension does Terraform expect for a JSON formatted configuration file?

Terraform expects native syntax for files named with a . tf suffix, and JSON syntax for files named with a . tf. json suffix.

How do I load a JSON file in Terraform?

If this JSON file is something you intend to include as part of your Terraform configuration (e.g. checked in to version control alongside the . tf files) then you can load the data structure from it into Terraform using the file function and the jsondecode function. The path.


1 Answers

It looks like you should use a template to compile the JSON before using in the definition

data "template_file" "task" {
  template = "${file("${task-definitions/example.json")}"

  vars {
    cpu = "${var.master_container_cpu}"
  }
}

In the JSON file you can reference the var using ${cpu}

Then you are able to use the output as your definition

container_definitions = "${data.template_file.task.rendered}"

like image 98
Stephen Avatar answered Sep 28 '22 04:09

Stephen