Format Dynamic Blocks in Terraform
Format dynamic blocks used for generating repeated nested blocks from lists and maps. Covers security group rules, IAM policies, and other common patterns.
Advanced Patterns
Detailed Explanation
Formatting Dynamic Blocks
Dynamic blocks replace repeated nested blocks with a programmatic approach. They add a level of complexity that makes formatting particularly important for understanding the generated structure.
Security Group 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 = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
description = ingress.value.description
}
}
dynamic "egress" {
for_each = var.egress_rules
content {
from_port = egress.value.from_port
to_port = egress.value.to_port
protocol = egress.value.protocol
cidr_blocks = egress.value.cidr_blocks
}
}
tags = {
Name = "web-sg"
}
}
IAM Policy Example
resource "aws_iam_policy" "custom" {
name = "custom-policy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket",
]
Resource = [
aws_s3_bucket.main.arn,
"${aws_s3_bucket.main.arn}/*",
]
}
]
})
}
Formatting Conventions
- Dynamic block structure:
dynamic "name" { for_each = ... content { ... } }has three levels of indentation - Content block alignment: Attributes inside
contentare aligned at the deepest nesting level - Iterator references:
ingress.value.from_portuses the dynamic block name as the iterator by default - Separation: Dynamic blocks are separated from static attributes by blank lines
Use Case
Creating security groups, IAM policies, load balancer listeners, or any resource with repeated nested blocks that vary based on input variables.