This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the jsonencode() function. The example file is on GitHub here.
Function name: jsonencode(value)
Returns: Takes a value and returns a properly JSON encoded version of that value. The value could be a string, list, map, or combination of primitives.
Example:
variable "list" {
default = ["one","two","three"]
}
# Returns ["one","two","three"]
output "json_output" {
value = "${jsonencoded(var.list)}"
}
##############################################
# Function: jsonencode
##############################################
##############################################
# Variables
##############################################
variable "simple_value" {
default = "Ford"
}
variable "simple_list" {
default = ["So", "long", "and", "thanks"]
}
variable "nested_list" {
default = [
["So"],
["Long"],
["and"],
["thanks!"],
]
}
variable "mixed_list" {
default = [
[
["3-1"],
"2-1",
],
[
["3-2"],
"2-2",
],
"1-1",
]
}
variable "bool_value" {
default = true
}
##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "1_simple_value_output" {
value = "${jsonencode(var.simple_value)}"
}
output "2_simple_list_output" {
value = "${jsonencode(var.simple_list)}"
}
output "3_nested_list_output" {
value = "${jsonencode(var.nested_list)}"
}
output "4_mixed_list_output" {
value = "${jsonencode(var.mixed_list)}"
}
output "5_bool_value_output" {
value = "${jsonencode(var.bool_value)}"
}
output "map_output" {
value = "${jsonencode(map("life",list("42"),"the universe",list("six","times","seven")))}"
}
Run the following from the jsonencode folder to get example output for a number of different cases:
#All examples are in variables
terraform apply
If the resource you are sending information to needs to be formatted correctly in JSON then I guess this is a good function to have in your back pocket. I would envision using this with the HTTP resource or an external resource that uses a custom script.
The function appears to be pretty boring. It’s basically outputting the value I know is in the variable in the format I used. But the important thing here is you may need that value as a string in JSON to pass along. If it’s a list or a map, you may need the whole list or map as a JSON encoded string, not the individual values in the primitive. You know who loves JSON? Lamba functions. Love it, live it, script it.
Coming up next is the keys() function. Yeah, yeah, yeah. We’re getting into maps.
Resourcely Guardrails and Blueprints
November 15, 2024
Deploying Azure Landing Zones with Terraform
November 12, 2024
October 18, 2024
What's New in the AzureRM Provider Version 4?
August 27, 2024