hcl2json: Convert Terraform HCL to JSON
hcl2json parses HCL (HashiCorp Configuration Language, as used by Terraform) into equivalent JSON, letting you query infrastructure config with jq.
HCL is hard to grep reliably. hcl2json turns a .tf file into JSON so you can pull a resource attribute or list every module source with jq in a CI check.
What it does
hcl2json reads an HCL file (as an argument or on stdin) and emits its JSON representation, where blocks become nested objects and repeated blocks become arrays. The output is exactly what Terraform itself would accept as .tf.json, so it round-trips.
Common usage
hcl2json main.tf | jq '.resource'
cat variables.tf | hcl2json | jq '.variable | keys'
# list every module source
hcl2json main.tf | jq -r '.module[][] | .source'Options
| Usage | What it does |
|---|---|
| hcl2json <file> | Convert a file and print JSON to stdout |
| cat f.tf | hcl2json | Read HCL from stdin |
| (pipe to jq) | hcl2json has no query flags; pair it with jq |
In CI
Use hcl2json to enforce policy without a full Terraform run: hcl2json main.tf | jq -e '.resource.aws_s3_bucket' fails when a bucket resource is absent. Because output is standard JSON, every jq check you know applies. Repeated blocks nest as arrays, so a resource path looks like .resource.aws_instance.web.
Common errors in CI
A malformed .tf prints an HCL diagnostic like "Argument or block definition required" or "Invalid expression" with the line and column. An empty result from jq usually means the block nesting differs from your path (resources are keyed by type then name). hcl2json evaluates the config structurally, so unresolved variables appear as interpolation strings, not their values.