How to Parse Terraform Output JSON in Python

Parse Terraform's JSON output into a flat dictionary of values using the standard library json module.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 11 views 0 copies

Python code

22 lines
Python 3.9+
import json

def parse_terraform_output(raw_output):
    """Parse Terraform JSON output into a flat dict of values."""
    try:
        data = json.loads(raw_output)
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON: {e}")

    return {key: value["value"] for key, value in data.items()}


if __name__ == "__main__":
    mock_terraform_output = """
    {
      "instance_id": {"value": "i-1234567890abcdef0"},
      "public_ip": {"value": "52.1.2.3"},
      "tags": {"value": {"Name": "web-server", "Env": "prod"}}
    }
    """
    parsed = parse_terraform_output(mock_terraform_output)
    print(json.dumps(parsed, indent=2))

Output

stdout
{
  "instance_id": "i-1234567890abcdef0",
  "public_ip": "52.1.2.3",
  "tags": {
    "Name": "web-server",
    "Env": "prod"
  }
}

How it works

The function parse_terraform_output accepts a JSON string and uses json.loads to convert it into a dictionary. Each key in the output maps to another dictionary containing a value field, so a dictionary comprehension extracts just those values. Error handling catches json.JSONDecodeError and raises a more descriptive ValueError. The __main__ block demonstrates usage with a mock output and prints the parsed result with json.dumps for readability.

Common mistakes

  • Not accounting for Terraform output that includes metadata like `sensitive` fields, which may need filtering.
  • Assuming the output is already a Python dict when it's often a JSON string from a subprocess.
  • Forgetting that nested values can be dicts or lists, not just scalars.

Variations

  1. Use `json.load` directly when reading from a file instead of `json.loads` on a string.
  2. Add type hints and a `TypedDict` for type-safe access in larger codebases.

Real-world use cases

  • Automating infrastructure provisioning: parse `terraform output` to pass IPs and IDs to configuration management tools.
  • Building CI/CD pipelines that need to consume Terraform state values for subsequent deployment steps.
  • Generating dynamic inventory files for Ansible or other orchestration tools based on cloud resources created by Terraform.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.