Table of Contents
What Are Dynamic Blocks?
Dynamic blocks let you generate repeated nested blocks (like ingress rules in a security group) from a variable or expression, instead of writing each one manually.
Basic Syntax
resource "aws_security_group" "web" {
name = "web-sg"
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
}
}
}
variable "ingress_rules" {
default = [
{ from_port = 80, to_port = 80, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"] },
{ from_port = 443, to_port = 443, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"] },
{ from_port = 22, to_port = 22, protocol = "tcp", cidr_blocks = ["10.0.0.0/8"] },
]
}
Iterator Renaming
Use iterator to rename the temporary variable:
dynamic "setting" {
for_each = var.settings
iterator = s
content {
namespace = s.value.namespace
name = s.value.name
value = s.value.value
}
}
Nested Dynamic Blocks
Dynamic blocks can be nested for complex structures:
dynamic "origin" {
for_each = var.origins
content {
domain_name = origin.value.domain
origin_id = origin.value.id
dynamic "custom_origin_config" {
for_each = origin.value.custom_config != null ? [origin.value.custom_config] : []
content {
http_port = custom_origin_config.value.http_port
https_port = custom_origin_config.value.https_port
origin_protocol_policy = custom_origin_config.value.protocol
}
}
}
}
Conditional Dynamic Blocks
Use an empty list to conditionally skip a dynamic block:
dynamic "logging" {
for_each = var.enable_logging ? [1] : []
content {
target_bucket = aws_s3_bucket.logs.id
target_prefix = "access-logs/"
}
}
When to Use Dynamic Blocks
Good use cases:
- Security group rules from a variable
- IAM policy statements
- CloudFront origins and cache behaviors
- Tags from a map
Avoid when:
- You have a fixed number of blocks (just write them out)
- Logic becomes hard to read (simplicity beats cleverness)
Learn More
- Terraform for Beginners Course — hands-on dynamic block labs
- Terraform By Example Book — real-world patterns
- Terraform Cheat Sheet — quick command reference



