How to export Terraform output values to JSON

Bjorn Krols

Bjorn Krols

Published on
10 May 2021

Terraform is a wonderful tool to set up and manage your infrastructure, but how can you integrate other tools and scripts with those Terraform-managed resources?

Output values are like the return values of a Terraform module, I will show you how to export those values to JSON; a popular, parsable, exchangeable format.

Output values are like the return values of a Terraform module.

Hello, World!

Create the following main.tf file containing the simplest possible "Hello, World!" module:

touch main.tf
terraform {
  required_version = "~> 0.15.0"
}

output "hello_world" {
  value = "Hello, World!"
}

infrastructure.json

Create the following apply.sh script:

touch apply.sh
#!/bin/bash

set -e

terraform apply
terraform output -json > ./infrastructure.json

The terraform apply command executes the actions proposed in a Terraform plan.

The terraform output command is used to extract the value of an output variable from the state file. The -json flag formats the output as a JSON object. The > redirection operator writes the output to the given file.

Execute apply.sh, a JSON file is created:

{
  "hello_world": {
    "sensitive": false,
    "type": "string",
    "value": "Hello, World!"
  }
}

You can use this JSON file with your favorite tools and scripts.

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this