Convert Terraform Locals Block to JSON
Convert Terraform locals blocks with computed values, expressions, and reusable named values from HCL to JSON format.
Detailed Explanation
Terraform Locals in HCL and JSON
The locals block defines named values within a module that can be referenced throughout the configuration. Unlike variables, locals are computed within the module and not exposed as inputs.
HCL Locals Definition
locals {
environment = "production"
project = "devtoolbox"
region = "us-east-1"
common_tags = {
Environment = "production"
Project = "devtoolbox"
ManagedBy = "terraform"
Team = "platform"
}
name_prefix = "devtoolbox-prod"
availability_zones = [
"us-east-1a",
"us-east-1b",
"us-east-1c"
]
}
JSON Structure
The locals block is unique because it has no labels. All attributes are direct children:
{
"locals": {
"environment": "production",
"project": "devtoolbox",
"region": "us-east-1",
"common_tags": {
"Environment": "production",
"Project": "devtoolbox",
"ManagedBy": "terraform",
"Team": "platform"
},
"name_prefix": "devtoolbox-prod",
"availability_zones": [
"us-east-1a",
"us-east-1b",
"us-east-1c"
]
}
}
Expression Locals
Locals often contain computed expressions:
locals {
subnet_count = 3
vpc_cidr = "10.0.0.0/16"
}
Expressions like length(var.availability_zones) or "${var.project}-${var.environment}" become strings in JSON.
Multiple Locals Blocks
HCL allows multiple locals blocks in the same file. In JSON, they merge into a single locals object. The converter handles this by collecting all local values together.
Locals vs Variables
While both define named values, variable blocks accept external input and locals blocks compute values internally. This distinction is preserved in the JSON structure.
Use Case
Defining shared values like common tags, naming conventions, and computed configuration across a Terraform module. Converting locals to JSON helps when building configuration generators or analyzing Terraform code structure programmatically.