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
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"}}}}}'
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}")
Drift Detection
terraform plan -detailed-exitcode -json 2>/dev/null
# Exit code 0 = no changes, Exit code 2 = drift detected
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)