In this article, we will look at theĀ jsonencode
Ā function in Terraform, explaining what it is, when, and why you might use it, along with many useful and practical examples you can follow along with!
We will cover:
- What is the jsonencode function in Terraform?
- What is the jsondecode function in Terraform?
- How to use the jsonencode Terraform function?
- Example 1: Using JSON files as input variables and local variables
- Example 2: Passing in JSON via environment variables
- Example 3: Decoding JSON strings to Terraform maps
- Example 4: Using jsonencode in the template file
- Example 5: Using jsonencode with the for loop
- Example 6: Creating IAM policies using jsonencode function
- Example 7: Creating Azure Policy definitions with jsonencode function
- What is the difference between jsonencode and heredoc Terraform?
jsonencode
is a Terraform function that encodes a given value to a string using JSON syntax. It can be useful wherever you need to deal with JSON input, for example, creating an IAM user in AWS, or Policy in Azure.
The opposite of theĀ jsonencode
function, theĀ jsondecode
Ā function in Terraform allows you to parse a JSON-formatted string and convert it into a data structure that you can use within your Terraform configurations.
It is useful wherever you need to convert your output to JSON and use the results elsewhere in your Terraform configuration.
Read more about other Terraform functions, expressions, and loops.
To play around with theĀ jsonencode
Ā function, you can use the Terraform console. Simply typeĀ terraform console
Ā into your terminal to start.
EnterĀ jsonencode({"hello"="world"})
ā The output displayed will be in JSON format.
Note that theĀ jsonencode
Ā cannot directly map to all types available in JSON formatting because there are differences between how the types are represented between HCL (Hashicorp configuration language) and JSON.
Terraform to JSON data types are mapped as follows:
string
ā Stringnumber
ā Numberbool
ā Boollist(...)
ā Arrayset(...)
ā Arraytuple(...)
ā Arraymap(...)
ā Objectobject(...)
ā Objectnull
ā Null value
For the following examples, we will create a simple JSON file:
yoda.json
{
"name": "Yoda",
"age": 900,
"city": "Dagobah System"
}
In this example, we will use the yoda.json file as an input variable, have Terraform use theĀ jsondecode
Ā function in the locals, and then finally output the results.
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
}
output "age" {
value = local.input_data.age
}
output "city" {
value = local.input_data.city
}
- We define a variableĀ
json_input
Ā to specify the path to the JSON input file. - We decode the JSON content using theĀ
jsondecode
Ā function and store it in theĀlocal.input_data
Ā variable. TheĀfile
function specifies we need to read the JSON contents from a file. - We define outputs for each key in the JSON, making the data available for other parts of your Terraform code. It can be referenced elsewhere in your Terraform code usingĀ
local.input_data.name
Ā ,Ālocal.input_data.age
Ā , andĀlocal.input_data.city
.
To run the code, in your terminal specify the variable directly with the -var
Ā flag, which points to the path of theĀ yoda.jsonĀ file:
terraform init
terraform apply -var="json_input=yoda.json"
In this example, we will define some JSON as an environment variable and pass it into our Terraform configuration.
To set the environment variables, run the following on the terminal:
export TF_VAR_json_input='{"name": "Yoda", "age": 900, "city": "Dagobah System"}'
Environment variables can be used to set Terraform variables usingĀ TF_VAR
.
The _json_imput
Ā part defines the name of the variable we want to set. This can then be referenced directly in the Terraform code (without the need for theĀ file
Ā function this time):
variable "json_input" {
description = "JSON input"
type = string
default = ""
}
locals {
input_data = jsondecode(var.json_input)
}
output "name" {
value = local.input_data.name
}
output "age" {
value = local.input_data.age
}
output "city" {
value = local.input_data.city
}
To see the results, run:
terraform init
terraform apply
In this example, we will output the values as a Terraform map and pass the JSON in directly on the terminal.
Note the outputs now have the values for each key contained in [""]
Ā .
variable "json_input" {
description = "JSON input"
type = string
default = ""
}
locals {
input_data = jsondecode(var.json_input)
}
output "name" {
value = local.input_data["name"]
}
output "age" {
value = local.input_data["age"]
}
output "city" {
value = local.input_data["city"]
}
To test the output we can run:
terraform init
terraform apply -var='json_input={"name": "Yoda", "age": 900, "city": "Dagobah System"}'
Suppose you have a template file, for example, a configuration file, and you want to include some data as a JSON-encoded string in that file.
Our template file looks like this:
{
"app_config": ${app_config}
}
Our terraform configuration looks like this:
example4.tf
# Define a variable with configuration data
variable "app_config" {
type = map(string)
default = {
name = "Yoda",
age = "900",
city = "Dagobah System"
}
}
# Render the template
data "template_file" "app_config_template" {
template = file("template.tpl")
vars = {
app_config = jsonencode(var.app_config)
}
}
# Create a local file to save the generated JSON config
resource "local_file" "app_config" {
filename = "app_config.json"
content = data.template_file.app_config_template.rendered
}
First, the data is defined that you want to encode as a JSON string. This data could be a variable or a map within your Terraform configuration.
Next, we use theĀ data "template_file"
Ā block to render a template file. TheĀ template
Ā attribute specifies the path to the template file, which isĀ template.tpl
. TheĀ vars
Ā attribute is used to pass variables into the template. In this case, we’re passing theĀ app_config
Ā variable, but we use theĀ jsonencode
Ā function to encode it as a JSON string.
Finally, we create a local file using theĀ resource "local_file"
Ā block. This local file is used to save the generated JSON configuration.
We specify theĀ filename
Ā attribute to set the path and name of the output file, which isĀ app_config.json
. TheĀ content
Ā attribute contains the rendered output from the template defined in theĀ data "template_file"
Ā block. This content is obtained usingĀ data.template_file.app_config_template.rendered
.
To run the example:
terraform init
terraform apply
On confirming the apply, a file called app_config.json will be generated in the local directory containing the map contents in JSON format:
{
"app_config": {"age":"900","city":"Dagobah System","name":"Yoda"}
}
You can useĀ jsonencode
Ā in conjunction with aĀ for
Ā loop in Terraform to generate JSON data structures dynamically. In this example, we have a list of items, which we will encode into a JSON array using a for
Ā loop.
OurĀ template.tplĀ file looks like this:
{
"items": ${items_json}
}
example5.tf:
# Define a list of items
variable "items" {
type = list(string)
default = ["Yoda", "Darth Vader", "Salacious Crumb"]
}
# 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
}
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 init
terraform apply
On confirmation of the apply, anĀ items.jsonĀ file is generated in the local directory containing the following JSON:
{
"items": [{"name":"Yoda"},{"name":"Darth Vader"},{"name":"Salacious Crumb"}]
}
Creating IAM policies in Terraform using theĀ jsonencode
Ā function can be useful when you need to define fine-grained permissions for your AWS resources.
IAM policies are defined as JSON documents, and you can use theĀ jsonencode
Ā function to create these policy documents in your Terraform configuration.
# Define a map of IAM policy statements
variable "iam_policy_statements" {
type = list(object({
action = list(string)
resource = string
}))
default = [
{
action = ["s3:GetObject", "s3:ListBucket"]
resource = "arn:aws:s3:::my-bucket/*"
},
{
action = ["s3:PutObject"]
resource = "arn:aws:s3:::my-bucket/upload/*"
},
# Add more policy statements as needed
]
}
# Encode the IAM policy using jsonencode
locals {
iam_policy_document = jsonencode({
Version = "2012-10-17",
Statement = [
for statement in var.iam_policy_statements : {
Action = statement.action,
Effect = "Allow",
Resource = statement.resource,
}
]
})
}
# Create an IAM policy
resource "aws_iam_policy" "example" {
name = "example-policy"
description = "Example IAM policy"
policy = local.iam_policy_document
}
# Attach the policy to a user, group, or role as needed
- The variableĀ
iam_policy_statements
Ā represents a list of IAM policy statements. Each statement includes anĀaction
Ā (a list of allowed actions) and aĀresource
Ā (the AWS resource that the actions apply to). - TheĀ
jsonencode
Ā function in theĀlocals
Ā block is used to generate the JSON document for the IAM policy. We use aĀfor
Ā loop to iterate over the policy statements defined in the variable and structure them into the required format for an IAM policy. - The IAM policy is created using theĀ
aws_iam_policy
Ā resource. TheĀpolicy
Ā attribute of this resource is set to the JSON-encoded IAM policy document from theĀlocals
Ā block. - Finally, you can attach the created policy to an IAM user, group, or role as needed by referencing theĀ
aws_iam_policy.example
Ā resource in the respective resource block (aws_iam_user_policy_attachment
,Āaws_iam_group_policy_attachment
, orĀaws_iam_role_policy_attachment
).
Azure Policy definitions are typically defined as JSON objects, and you can useĀ jsonencode
Ā to create those JSON objects within your Terraform configuration.
The below example shows an Azure policy rule enforcing restrictions if certain tags are applied, which can be referenced elsewhere in your code by referring to policy_rule
.
# Define an Azure Policy definition
resource "azurerm_policy_definition" "example" {
name = "example-policy"
display_name = "Example Policy"
description = "An example Azure Policy definition"
policy_type = "Custom"
mode = "All"
metadata {
category = "General"
}
# Encode the policy rule using jsonencode
policy_rule = jsonencode({
if {
allOf = [
{
field = "tags['environment']"
equals = "production"
},
{
field = "tags['costCenter']"
notLike = "HR-*"
}
]
}
then {
effect = "deny"
}
})
}
After defining the policy, you can associate it with a policy assignment to enforce it within a particular scope, such as the subscription level:
resource "azurerm_policy_assignment" "example" {
name = "example-assignment"
scope = "/subscriptions/<subscription_id>"
policy_definition_id = azurerm_policy_definition.example.id
}
Where,Ā jsonencode
is specifically for encoding structured data into a JSON string, making it suitable for creating JSON-based configuration files or policy definitions, Heredoc is a way to include multi-line strings directly in your Terraform configuration.
It allows you to define a block of text without escaping special characters or worrying about JSON formatting. Heredoc is often used for embedding text, scripts, or configuration files in your Terraform code.
For reference, Heredoc syntax within a resource block looks like the below:
resource "example_resource" "example" {
config_script = <<-EOT
echo "This is a sample script"
EOT
}

As Sqills grew and transitioned to the cloud, it was no longer practical or desirable to have the infrastructure engineers automate Terraform with Bash scripts. They needed a low-maintenance Terraform automation solution they could depend on ā and thatās when they discovered Spacelift.
Handling JSON files in your Terraform configuration files can be achieved using theĀ jsonencode
Ā and the opposite jsondecode
functions. Data structures can be manipulated as needed to read in or create new JSON files for common purposes, such as IAM assignments in AWS or creating Azure Policy.
We encourage you also to exploreĀ how Spacelift makes it easy to work with Terraform. If you need any help managing your Terraform infrastructure, building more complex workflows based on Terraform, and managing AWS credentials per run, instead of using a static pair on your local machine, Spacelift is a fantastic tool for this.Ā It supports Git workflows, policy as code, programmatic configuration, context sharing, drift detection, and many moreĀ greatĀ features right out of the box. You can check it for free, byĀ creating a trial account.
Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands Terraformās existing concepts and offerings. It is a viable alternative to HashiCorpās Terraform, being forked from Terraform version 1.5.6.
Manage Terraform Better with Spacelift
Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization and many more.