DEV Community

Alex Spinov
Alex Spinov

Posted on

Terraform Has a Free JSON API That Most DevOps Engineers Miss

Terraform CLI and Terraform Cloud both expose APIs that let you manage infrastructure state, trigger runs, and inspect plans programmatically.

Terraform CLI JSON Output

Every Terraform command supports machine-readable JSON:

terraform plan -json -out=plan.tfplan
terraform show -json plan.tfplan
terraform output -json
terraform show -json
Enter fullscreen mode Exit fullscreen mode

Terraform Cloud API

Free tier available with full REST API:

curl -H "Authorization: Bearer $TF_TOKEN" \
  https://app.terraform.io/api/v2/organizations/my-org/workspaces

curl -X POST -H "Authorization: Bearer $TF_TOKEN" \
  -H "Content-Type: application/vnd.api+json" \
  https://app.terraform.io/api/v2/runs \
  -d '{"data":{"type":"runs","relationships":{"workspace":{"data":{"type":"workspaces","id":"ws-abc123"}}}}}'
Enter fullscreen mode Exit fullscreen mode

Building a Cost Estimator

import json, subprocess

result = subprocess.run(
    ["terraform", "show", "-json", "plan.tfplan"],
    capture_output=True, text=True
)
plan = json.loads(result.stdout)

for change in plan["resource_changes"]:
    action = change["change"]["actions"]
    resource_type = change["type"]
    name = change["name"]
    if "create" in action:
        print(f"  + {resource_type}.{name}")
    elif "delete" in action:
        print(f"  - {resource_type}.{name}")
Enter fullscreen mode Exit fullscreen mode

Drift Detection

terraform plan -detailed-exitcode -json 2>/dev/null
# Exit code 0 = no changes, Exit code 2 = drift detected
Enter fullscreen mode Exit fullscreen mode

Why This Matters

  • Policy enforcement: Parse plan JSON to block risky changes in CI
  • Cost tracking: Estimate costs before every apply
  • Compliance auditing: Query state to verify security configs

Need custom infrastructure tooling or automated DevOps pipelines? I build developer tools and automation. Check out my web scraping actors on Apify or reach out at spinov001@gmail.com for custom solutions.

Top comments (0)