Introduction
This guide demonstrates how to use the local_file resource with the jsonencode and templatefile functions to output a map of values to a text file. In the example a variable is used with a map structure, however the idea is the same when using data resources or resources directly.
Expected Outcome
After completing this guide, you will have a text file containing formatted data derived from your Terraform configuration.
Use Case
This approach is useful when you need to export data from your Terraform configuration, such as resource attributes, for use in external scripts or for documentation purposes.
Procedure
This procedure outlines two methods for formatting and saving data to a local file: as a JSON object and as custom-formatted text using a template.
Step 1: Define the Input Data
First, define a map variable in your Terraform configuration. This example uses a variable with a default map, but you can adapt this to use data from resources or other data sources.
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
}
}
}Method 1: Output as a JSON File
This method uses the jsonencode function to convert the map into a JSON string.
-
Create a
local_fileresource that uses thejsonencodefunction to set the file's content.resource "local_file" "items_to_json" { content = jsonencode(var.items) filename = "${path.module}/items_json.txt" } -
After running
terraform apply, Terraform creates a file nameditems_json.txtwith the following content.{"first":{"age":49,"name":"Mabel"},"second":{"age":52,"name":"Andy"},"third":{"age":25,"name":"Pete"}}
Method 2: Output as a Formatted Text File
This method uses the templatefile function to render a string from a template, giving you full control over the output format.
-
Create a template file named
items.tftplin the same directory.%{ 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_fileresource that uses thetemplatefilefunction to generate the file's content.resource "local_file" "items_to_template" { content = templatefile("items.tftpl", { items = var.items }) filename = "${path.module}/items_formatted.txt" } -
After running
terraform apply, Terraform creates a file nameditems_formatted.txtwith the following content.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
- The
contentattribute of thelocal_fileresource only accepts a string value. You must first transform complex types like maps or objects into a string using a function likejsonencodeortemplatefile. - For more details, refer to the official documentation: