HashiCorp Terraform provides a couple functions for working with JSON. These are the jsonencode and jsondecode functions and they grant the ability to encode and decode JSON. This can be a powerfull tool for several scenarios where you may need to work with JSON data within a Terraform project. This article shows some simple examples of using the jsonencode and jsondecode functions, along with a full example on how to load a JSON file and reference its values within Terraform code.

Let’s dig in!

jsonencode and jsondecode Functions

To start, the following two functions in Terraform are used for encoding and decoding JSON. This will enable you to read JSON data / files, or write data strutured as JSON.

  • jsonencode – Encodes the given Terraform data type value to a JSON formatted string.
  • jsondecode – Decodes given string of JSON, and returns a Terraform data type representation of the decoded JSON.

The following are a couple really basic examples of calling the jsonencode and jsondecode functions:

locals {
  # ENCODE JSON
  boolean_json = jsonencode(true)
  # Encoded JSON result will be:
  # boolean_json = "true"

  object_json = jsonencode({"site" = "build5nines.com"})
  # Encoded JSON result will be:
  # object_json = "{\"site\":\"build5nines.com\"}"

  # DECODE JSON
  boolean_val = jsondecode("true")
  # Decoded result will be Terraform object:
  # boolean_val = true
  
  object_val = jsondecode("{\"site\": \"build5nines.com\"}")
  # Decoded result will be Terraform object:
  # object_val = {
  #  "site" = "build5nines.com"
  # }
}

Now, let’s take a look at some practical examples of using these methods to perform common tasks of working with JSON in Terraform.

Load JSON Data from File

There may come times when you need to load data or configuration values from a JSON file. There are several reasons you may need to do this. The important thing is that you need to import a JSON file into your Terraform project, parse that JSON file, and read values or data from it for your Terraform configuration.

Load JSON File into Terraform Project

Let’s say you have the following example JSON file named data.json in the root path of your Terraform project that you need to load:

{
    "environment": "staging",
    "config_val_string": "abc",
    "config_val_number": 222
}

The jsondecode function can be used to decode the JSON contents of the file, but first you need to read the file into your Terraform project. To read a file into Terraform, the file function can be used.

The following is the file function call that can be used to load the data.json file:

file("${path.module}/data.json")

Notice, the ${path.module} within the file name string for the data.json file. This will build a full path to the JSON file that is stored within the same folder as the Terraform project, or Terraform module that contains this code.

Once the file function is called, the result of the function all will be the contents of the JSON file.

Parse JSON from File

Once you have loaded the contents of the JSON file into your Terraform project, then you need to call the jsondecode function, passing it the JSON file contents. The result from the jsondecode function will be a Terraform data type that represents the data in the JSON file. For the example given previously, this will be a Terraform object that contains the properties and data from the JSON file.

The following is an example of calling the jsondecode function, along with the file function together, to both load and decode the JSON file in a single line and assign it to a local variable:

locals {
  json_data = jsondecode(file("${path.module}/data.json"))
}

The resulting local.json_data variable will then be a decoded object that represents the data that’s contained within the JSON file. The value will be the appropriate Terraform object type.

Accessing Properties from Decoded JSON File

Now that the JSON file has been loaded and decoded, the local.json_data variable can now be referenced within the Terraform project to access the values and data contained within the file.

The following is an example of assigning a resource parameter to a value that’s contained within the JSON file:

resource "azurerm_resource_group" "primary_rg" {
  # some parameters not show in this example

  tags = {
    # Get the 'environment' property value from the JSON file
    environment = local.json_data.environment
  }
}

Notice, the environment property of the JSON object can be accessed directly on the local.json_data Terraform object. This is because the JSON contents fo the file have been parsed and the local.json_data Terraform object contains the appropriate Terraform object representation for the JSON defined within the data.json file.

If you notice, the example data.json file also contains a number property named config_val_number. This property can be accessed exactly the same way:

local.json_data.config_val_number
# returns 222 (as a 'Number' Terraform type)

Load Terraform Input Variables from JSON

When calling Terraform plan and apply at the command-line, the -var-file parameter can be used to pass in a file that contains any input variables needed for the Terraform project. The most common format is to use a .tfvars file in HCL format to define the variables. However, the Terraform input variables can also be defined in a .tfvars.json file alternatively that uses JSON instead.

The following is an example inputvariables.tfvars.json file that might be used for the input variables for a Terraform project:

{
  "location": "eastus",
  "vm_ip_allow_list": [
    '10.50.0.1/32'
    '10.83.0.5/32'
  ]
}

The following is an example of calling terraform apply at the command-line and passing in the .tfvars.json file to define the input variables for the Terraform project:

terraform apply \
  -var-file 'inputvariables.tfvars.json'

Related: The “Use Terraform Input Variables to Parameterize Infrastructure Deployments” article covers more details on defining and using Terraform input variables.

Conclusion

JSON has become a standard format for defining all sorts of data, and has largely replaced the use of XML in software projects of all types. The Terraform jsonencode and jsondecode functions are rather simple to use and grant the ability to decode / parse and encode JSON data directly within a Terraform project. This is extremely useful at times when the infrastructure as code project needs to work with JSON files directly.

Chris Pietschmann is a Microsoft MVP, HashiCorp Ambassador, and Microsoft Certified Trainer (MCT) with 20+ years of experience designing and building Cloud & Enterprise systems. He has worked with companies of all sizes from startups to large enterprises. He has a passion for technology and sharing what he learns with others to help enable them to learn faster and be more productive.
Microsoft MVP HashiCorp Ambassador

Discover more from Build5Nines

Subscribe now to keep reading and get access to the full archive.

Continue reading