Dynamic Blocks
count and for_each repeat whole resources. Some resources take repeated nested blocks instead: ingress { } rules in an aws_security_group, setting { } in an Elastic Beanstalk environment, rule { } in an S3 lifecycle configuration. A dynamic block generates those from a collection.
dynamic "ingress" { # the nested block's name
for_each = var.ingress_rules # a list, set or map
content { # the body of each generated block
from_port = ingress.value.port # the iterator is named after the block
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ingress.value.cidrs
}
}The iterator has .key (map key or list index) and .value; rename it with iterator = rule when nesting dynamic blocks.
A security group from a variable
This session plans the security group offline with the teaching provider setup from Data Sources, then reads the generated blocks out of the saved plan:
mkdir sg && cd sg
cat > offline.tf <<'HCL'
provider "aws" {
region = "eu-west-1"
access_key = "offline"
secret_key = "offline"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
}
HCL
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
variable "ingress_rules" {
type = map(object({
port = number
cidrs = list(string)
}))
default = {
https = { port = 443, cidrs = ["0.0.0.0/0"] }
ssh = { port = 22, cidrs = ["10.0.0.0/16"] }
}
}
resource "aws_security_group" "web" {
name = "web"
description = "Web tier"
vpc_id = "vpc-0123456789abcdef0"
dynamic "ingress" {
for_each = var.ingress_rules
content {
description = ingress.key
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ingress.value.cidrs
}
}
}
HCL
tofu init >/dev/null
tofu plan -out=tfplan >/dev/null
tofu show -json tfplan | jq -c '.resource_changes[0].change.after.ingress[] | {description, from_port, cidr_blocks}'
echo "--- without the ssh rule"
tofu plan -out=tfplan -var 'ingress_rules={ https = { port = 443, cidrs = ["0.0.0.0/0"] } }' >/dev/null
tofu show -json tfplan | jq -c '.resource_changes[0].change.after.ingress[] | {description, from_port}'{"description":"https","from_port":443,"cidr_blocks":["0.0.0.0/0"]}
{"description":"ssh","from_port":22,"cidr_blocks":["10.0.0.0/16"]}
--- without the ssh rule
{"description":"https","from_port":443}
Maps are iterated in key order, so https comes before ssh. An empty collection generates no blocks at all, which is also how you make an optional nested block: for_each = var.logging_bucket == null ? [] : [var.logging_bucket].
Optional nested blocks
resource "aws_s3_bucket_lifecycle_configuration" "logs" {
bucket = aws_s3_bucket.logs.id
rule {
id = "expire"
status = "Enabled"
filter {}
expiration {
days = var.retention_days
}
# present only when a transition is requested
dynamic "transition" {
for_each = var.archive_after_days == null ? [] : [var.archive_after_days]
content {
days = transition.value
storage_class = "GLACIER"
}
}
}
}Use them sparingly
Dynamic blocks hide the shape of a resource behind a loop. Prefer:
- Separate resources when the provider offers them. For security groups,
aws_vpc_security_group_ingress_rulewithfor_eachgives each rule its own address, so adding a rule doesn't rewrite the group, and rules can't silently fight with rules defined elsewhere (Security Groups in Code). - Literal blocks when there are two or three fixed ones. Readers see them directly.
Dynamic blocks earn their place inside reusable modules, where the caller decides how many nested blocks there are.
Test yourself
Inside dynamic "ingress" { for_each = var.rules ... }, how do you reach the current rule's port?
each.value.portingress.value.portvar.rules.portdynamic.value.port
How do you generate a nested block only when var.x is not null?
count = var.x == null ? 0 : 1inside the blockfor_each = var.x == null ? [] : [var.x]enabled = var.x != null- It isn't possible
Why are separate aws_vpc_security_group_ingress_rule resources often better than dynamic ingress blocks?
- They are faster to apply
- Each rule gets its own address, so changes touch only that rule
- Dynamic blocks are deprecated
- They don't need a VPC