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.
Python code
22 linesimport 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
{
"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
- Use `json.load` directly when reading from a file instead of `json.loads` on a string.
- 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
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.