Convert Terraform Dynamic Blocks to JSON
Convert Terraform dynamic blocks that generate repeated nested blocks from HCL to JSON, including for_each and content blocks.
Detailed Explanation
Terraform Dynamic Blocks
Dynamic blocks allow you to generate repeated nested blocks based on a collection. They replace manual repetition of similar blocks with a programmatic approach.
HCL Dynamic Block Example
resource "aws_security_group" "web" {
name = "web-sg"
description = "Security group for web servers"
vpc_id = "aws_vpc.main.id"
dynamic "ingress" {
for_each = [80, 443, 8080]
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
JSON Structure
Dynamic blocks translate to JSON as nested objects preserving the dynamic, for_each, and content structure:
{
"resource": {
"aws_security_group": {
"web": {
"name": "web-sg",
"dynamic": {
"ingress": {
"for_each": [80, 443, 8080],
"content": {
"from_port": "ingress.value",
"to_port": "ingress.value",
"protocol": "tcp",
"cidr_blocks": ["0.0.0.0/0"]
}
}
}
}
}
}
}
for_each vs count
Dynamic blocks use for_each to iterate over collections. The iterator variable (ingress.value in this case) references the current element. In JSON, these references become strings.
Nested Dynamic Blocks
Dynamic blocks can be nested within other dynamic blocks for complex configurations like multi-level security group rules with conditions.
Content Block
The content sub-block defines the structure of each generated block. Its attributes can reference the iterator using <label>.key and <label>.value.
Use Case
Creating security groups with multiple ingress rules, defining IAM policies with multiple statements, or any scenario where repeated nested blocks need to be generated from a data structure.