Terraform: using json files as input variables and local variables

Specifying input variables in the “terraform.tfvars” file in HCL syntax is commonly understood.   But if the values you need are already coming from a json source, it might make more sense to feed those directly to Terraform.

Here is an example where the simple variable “a” is provided via an external json file.

# input variables file in json format (versus HCL)
$ cat variable-values.json
{ "a": "123" }

$ cat main.tf
variable a { default="n/a" }

output "show_var_a" {
  value = var.a
}

$ terraform init
$ terraform apply -var-file=variable-values.json -auto-approve
...
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:

show_var_a = "123"

This works for simple string values as shown above, but also complex arrays, maps, and complex data structures.

It is also possible to load local variables from an external json file using ‘jsondecode’.  Here is how you would pull “mylocal”.

# local variables files in json format
$ cat local-values.json
{ "mylocal": "is local" }

$ cat main.tf
locals {
  local_data = jsondecode(file("${path.module}/local-values.json"))
}

output "show_locals" {
  value = local.local_data.mylocal
}

$ terraform init 
$ terraform apply -auto-approve 
... 
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

show_locals = "is local"

We’ve shown the simple string example here, but this also works for arrays, maps, and complex data structures.

For a full example, see my json_vars_file folder on github.  Retrieve the files then run:

./apply.sh

 

REFERENCES

terraform, tomap

devopsslice, jsondecode for locals

terraform, learn about locals