Dynamic Blocks
A dynamic block builds repeated nested blocks from a list or a map. It writes the block once and lets the data decide how many copies appear.
One list of values
The list holds the data. The block below reads it, so the data is the only thing that changes.
variable "ports" {
type = list(number)
default = [80, 443]
}One block per port
Each port in the list becomes one ingress block. This is the same block the closing example runs.
resource "aws_security_group" "web" {
name = "web"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}An empty list builds nothing
With no items in the list, the dynamic block adds no nested blocks.
dynamic "ingress" {
for_each = []
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
}
}Example
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "6.72.0"
}
}
}
provider "aws" {
region = "us-east-1"
s3_use_path_style = true
endpoints {
s3 = "http://localhost:5000"
ec2 = "http://localhost:5000"
}
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
}
variable "ports" {
type = list(number)
default = [80, 443]
}
resource "aws_security_group" "web" {
name = "web"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
output "rules" {
value = [for p in var.ports : "Port ${p} from 0.0.0.0/0."]
}
# Commands (with dummy credentials for the emulator):
# export AWS_ACCESS_KEY_ID=test
# export AWS_SECRET_ACCESS_KEY=test
# terraform init
# terraform apply -auto-approve
# terraform destroy -auto-approveKey points
- Some resources need the same nested block many times.
- Copying the block by hand grows long and drifts apart.
- A dynamic block repeats the nested block for each item in a list.
- The label after the dynamic keyword names the block it builds.
- Inside the block, each value is read through the iterator, such as rule.value.
- An empty list builds no blocks at all.
- A security group is a firewall around a server. Each ingress rule opens one port to one set of addresses.
- 0.0.0.0/0 is a CIDR block that means every address. The rule applies to traffic from anywhere.
The list holds two ports. The dynamic block builds one ingress rule for each port, so the security group opens 80 and 443 with no repeated block. The security group is built in the mock cloud, so the ports open nowhere real.
Note
The pattern is the same as a for loop, but it builds blocks instead of values.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What happens when you add a third rule to a list used by a dynamic block?