Convert HCL Maps and Lists to JSON
Learn how HCL maps (objects) and lists (arrays) translate to JSON. Covers map literals, list literals, and their use in Terraform configurations.
Detailed Explanation
Maps and Lists in HCL
HCL has native syntax for maps (key-value collections) and lists (ordered sequences) that map directly to JSON objects and arrays. Understanding this mapping is essential for working with Terraform's JSON syntax.
HCL Map Syntax
locals {
tags = {
Environment = "production"
Team = "platform"
Project = "devtoolbox"
ManagedBy = "terraform"
}
}
Maps use curly braces with key = value syntax. In JSON, these become regular objects:
{
"locals": {
"tags": {
"Environment": "production",
"Team": "platform",
"Project": "devtoolbox",
"ManagedBy": "terraform"
}
}
}
HCL List Syntax
variable "availability_zones" {
default = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
variable "ports" {
default = [80, 443, 8080]
}
Lists use square brackets with comma-separated values, identical to JSON arrays.
Nested Collections
Maps can contain lists and vice versa:
locals {
services = {
web = ["nginx", "apache"]
db = ["postgres", "redis"]
}
}
Map vs Block
A common source of confusion is the difference between map attributes and blocks. Maps use = assignment, while blocks do not. In JSON, both become objects, but their semantic meaning in Terraform differs.
Use Case
Defining common tags, configuring security group rules with multiple CIDR blocks, setting up variable defaults with complex data structures, or any Terraform configuration that uses collections of values.