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?
- Terraform jsonencode function use case examples
- What is the difference between jsonencode and jsondecode in Terraform?
- What is the difference between jsonencode and heredoc in Terraform?
The jsonencode
function in Terraform converts a Terraform value (such as a map, list, or object) into a JSON-formatted string. It’s typically used when a resource or module expects a JSON string input, such as an IAM policy in AWS or a role definition in Azure.Ā
The jsondecode
function in Terraform converts a JSON-formatted string into a native Terraform value (map, list, string, number, etc.). It is the opposite of the jsonencode
function and is typically used to parse external data passed as a JSON string, such as data from a file, remote source, or environment variable.Ā
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:
Terraform type | JSON equivalent | Information lost |
string |
String | None |
number |
Number | None |
bool |
Boolean | None |
list(...) |
Array | None |
tuple([...]) |
Array | Element types |
set(...) |
Array | Ordering and uniqueness not guaranteed |
map(...) |
Object | None |
object({...}) |
Object | Attribute types |
null |
null | None |
JSON lacks constructs for distinguishing set
from list
, or object
from map
, so type constraints and uniqueness/order guarantees are lost.
For the following examples, we will create a simple JSON file:
yoda.json
{
"name": "Yoda",
"age": 900,
"city": "Dagobah System"
}
Example 1: Using JSON files as input variables and local variables
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. You can reference it elsewhere in your Terraform code using
local.input_data.name
,local.input_data.age
, andlocal.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"
Example 2: Passing in JSON via environment variables
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
Example 3: Decoding JSON strings to Terraform maps
In this example, we will output the values as a Terraform map and pass the JSON in directly on the terminal.
Note that 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"}'
Example 4: Using jsonencode in the template file
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, you define the data 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"}
}
Example 5: Using jsonencode with the for loop
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"}]
}
Example 6: Creating IAM policies using jsonencode function
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 anaction
(a list of allowed actions) and aresource
(the AWS resource to which the actions apply). - The
jsonencode
function in thelocals
block generates the JSON document for the IAM policy. We use afor
loop to iterate over the policy statements defined in the variable and structure them into the required format. - The IAM policy is created using the
aws_iam_policy
resource. This resource’spolicy
attribute is set to the JSON-encoded IAM policy document from thelocals
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
, oraws_iam_role_policy_attachment
).
Example 7: Creating Azure Policy definitions with jsonencode function
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. You can reference it 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
}
jsonencode
converts a Terraform expression (like a map or list) into a valid JSON string. Itās commonly used when passing structured data to APIs or templates that expect JSON. jsondecode
does the reverse. It parses a JSON string and turns it into a Terraform expression you can use in logic or interpolation.
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.
Heredoc allows you to define a block of text without escaping special characters or worrying about JSON formatting. It is often used to embed text, scripts, or configuration files in your Terraform code.
For reference, Heredoc syntax within a resource block looks like the following:
resource "example_resource" "example" {
config_script = <<-EOT
echo "This is a sample script"
EOT
}
Use jsonencode
when precision and structural correctness matter, such as rendering data for APIs or configuration files and heredoc
for readable templates or inline file content.

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.
Terraform is really powerful, but to achieve an end-to-end secure Gitops approach, you need to use a product that can run your Terraform workflows. Spacelift takes managing Terraform to the next level by giving you access to a powerful CI/CD workflow and unlocking features such as:
- Policies (based on Open Policy Agent) ā You can control how many approvals you need for runs, what kind of resources you can create, and what kind of parameters these resources can have, and you can also control the behavior when a pull request is open or merged.
- Multi-IaC workflows ā Combine Terraform with Kubernetes, Ansible, and other infrastructure-as-code (IaC) tools such as OpenTofu, Pulumi, and CloudFormation,Ā create dependencies among them, and share outputs
- Build self-service infrastructure ā You can use Blueprints to build self-service infrastructure; simply complete a form to provision infrastructure based on Terraform and other supported tools.
- Integrations with any third-party tools ā You can integrate with your favorite third-party tools and even build policies for them. For example, see how to integrate security tools in your workflows using Custom Inputs.
Spacelift enables you to create private workers inside your infrastructure, which helps you execute Spacelift-related workflows on your end. Read the documentation for more information on configuring private workers.
You can check it out for free by creating a trial account or booking a demo with one of our engineers.
Using the JSON encode and the opposite jsondecode
functions, you can handle JSON files in your Terraform configuration files. 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.
Frequently asked questions
What does jsonencode() do in Terraform?
jsonencode()
converts any valid Terraform value (string, number, list, map, object, etc.) into a compact JSON string. It minifies the output by design, removing all unnecessary whitespace.Ā
How to escape quotes or special characters?
Escaping is handled automatically. For example, double quotes ("
) inside strings become \"
, and newline characters become \n
. You donāt need to manually escape special characters unless you’re nesting the resulting JSON inside another string (e.g., a template or shell command), in which case you might need additional escaping layers.
Does jsonencode pretty-print?
No, jsonencode()
always emits one-line, minified JSON. This behavior is by design and cannot currently be changed.
To pretty-print the JSON for readability, you can:
- Pipe the value through the Terraform console:
terraform console <<< 'jsonencode(var.example)' | jq
- Use
templatefile()
with manual indentation logic (though it’s tedious and error-prone).
Is the encoded JSON stored in the state file?
Yes. If you use jsonencode()
inside a local
, output
, or resource
block, its result can be persisted in the Terraform state file.
As a best practice:
- Mark outputs containing sensitive data with
sensitive = true
- Use secure state backends (e.g., S3 with encryption, Terraform Cloud, etc.)
- Avoid placing secrets in values encoded via
jsonencode()
, if possible
Does jsonencode support YAML?
No. jsonencode()
is strictly for JSON. For YAML support, use yamlencode()
to convert a Terraform value to YAML and yamldecode()
to parse YAML into a Terraform value.
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.