How to Use JSON or YAML Data in terraform.tfvars-Style HCL

Terraform variable files (.tfvars) use HCL assignment syntax. If your variable values exist as JSON (from an API, a secrets manager, or a config file) or YAML (from an existing application config), converting them to HCL format is a regular infrastructure workflow task.

What tfvars HCL looks like

# terraform.tfvars
environment    = "production"
instance_count = 3
instance_type  = "t3.medium"

tags = {
  Project     = "my-app"
  Environment = "production"
  Owner       = "platform-team"
}

allowed_cidr_blocks = [
  "10.0.0.0/8",
  "172.16.0.0/12"
]

This is distinct from the variable declarations in .tf files — those use variable "name" {} blocks. The .tfvars file just assigns values using HCL's key-value syntax.

How types map from JSON/YAML to HCL

JSON typeJSON exampleHCL equivalent
String"production""production"
Number33
Booleantruetrue
Nullnullnull
Array["a","b"]["a", "b"]
Object{"key":"val"}{key = "val"}

The main HCL difference from JSON: object keys don't require quotes, and the key-value separator is = not :.

YAML-specific considerations

YAML has implicit type coercion that can cause problems when converting to HCL:

  • YAML's yes/no/on/off become booleans in YAML 1.1 parsers — these need to be converted to true/false for HCL
  • YAML multiline strings (block scalars with | or >) become single-line strings with escaped newlines in HCL
  • YAML anchors and aliases don't exist in HCL — they're expanded to their referenced values

A practical conversion

Given this JSON from a configuration API:

{
  "environment": "staging",
  "replicas": 2,
  "feature_flags": {"new_ui": true, "beta_api": false},
  "allowed_origins": ["https://app.example.com", "https://staging.example.com"]
}

The equivalent HCL for a .tfvars file:

environment = "staging"
replicas    = 2

feature_flags = {
  new_ui   = true
  beta_api = false
}

allowed_origins = [
  "https://app.example.com",
  "https://staging.example.com"
]
Validate after converting: run terraform validate after placing the converted tfvars file in your working directory. Type mismatches — a string value where Terraform expects a number — surface here with clear error messages before any infrastructure changes happen.