Introduction
This article explains how to leverage the local_file resource in combination with the functions jsonencode and templatefile to output a map of values to a text file.
Use case:
When having many instances of a resource and want to output these to a file as JSON or as some formatted text so you can use them in other scripting or documentation that you have.
Below is a generalized example on how to generate a formatted text file from Terraform values.
In the example a variable is used with a map structure, however the idea is the same when using data resources or resources directly.
Procedure
We have the following variable with a map containing three elements:
variable"items" {
type=map(any)
description="Example map variable"
default={
"first" = { name = "Mabel", age = 49 },
"second" = { name = "Andy", age = 52 },
"third" = { name = "Pete", age = 25 }
}
}
Output variable as JSON file
Create a local_file resource with the following code:
resource"local_file""items_to_json" {
content = jsonencode(var.items)
filename = "${path.module}/items_json.txt"
}
Here the jsonencode function is used to transform the variable items into a JSON string.
The local_file resource will then redirect this string to a file specified in filename variable.
The contents of the output file will be:
{"first":{"age":49,"name":"Mabel"},"second":{"age":52,"name":"Andy"},"third":{"age":25,"name":"Pete"}}
Output variable as formatted text file
Create a template file item.tftpl with the following content:
%{ for item_key, item_value in items ~}
${item_key}: "My name is ${item_value.name} and my age is ${item_value.age}".
%{ endfor ~}
Create a local_file resource with the following code:
resource"local_file""items_to_template" {
content = templatefile("items.tftpl", { items = var.items })
filename = "${path.module}/items_formatted.txt"
}
Here the templatefile function is used to transform the variable items into a formatted string.
The local_file resource will direct this string to a file specified in filename variable.
The contents of the output file will be:
first: "My name is Mabel and my age is 49".
second: "My name is Andy and my age is 52".
third: "My name is Pete and my age is 25".
Additional Information
A note about the local_file resource:
The content attribute only accepts strings. This means you can not use the variable directly. You will first need to transform it into a string. Here showcased with jsonencode and templatefile.
Documentation