Dynamic Blocks
Imagine you’re designing your Lego city with Terraform. Some buildings like apartments have repeating patterns: multiple identical floors, each with slightly different details.
Instead of writing the same block over and over, Terraform gives you dynamic blocks. They act like a “loop inside a resource,” letting you generate repeated nested configurations based on variables or lists. Dynamic blocks make your code cleaner, more flexible, and easier to maintain.
Key Concepts
1. What is a Dynamic Block?
- A dynamic block allows you to programmatically generate nested blocks inside a resource.
- Useful when the number of nested blocks depends on variables or lists.
dynamic "<block_name>" {
for_each = <list or map>
content {
# nested arguments
}
}
2. Example: Security Group Rules
Instead of writing multiple ingress rules manually:
resource "aws_security_group" "example" {
name = "example-sg"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
You can use a dynamic block:
variable "ports" {
default = [80, 443]
}
resource "aws_security_group" "example" {
name = "example-sg"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
3. Example: Tags with Dynamic Blocks
variable "tags" {
default = {
Environment = "dev"
Owner = "Shubham"
}
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
dynamic "tags" {
for_each = var.tags
content {
key = tags.key
value = tags.value
}
}
}
Hands‑On Lab / Demo
Lab: Dynamic Subnets
- Run
terraform apply→ Subnets are created dynamically inside the VPC.
Use dynamic block in VPC module:
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
dynamic "subnet" {
for_each = var.subnets
content {
cidr_block = subnet.value
}
}
}
Define subnets list:
variable "subnets" {
default = ["10.0.1.0/24", "10.0.2.0/24"]
}
Pro Tips & Best Practices
- Use dynamic blocks for nested repetition, not for top‑level resources (use
for_eachorcountthere). - Keep dynamic block logic simple - avoid deeply nested loops.
- Always test with
terraform planto confirm generated blocks. - Document why a dynamic block is used - it can be harder to read than static code.
- Prefer readability over cleverness - sometimes explicit blocks are clearer.
Summary & Cheatsheet
- Dynamic blocks = Loops inside resources.
- Syntax:
dynamic "<block_name>" { for_each = <list> content { … } } - Use cases: Security group rules, tags, nested subnets.
- Best practice: Use for nested repetition, keep logic simple.
Quick mnemonic: Dynamic = Repeat Smartly
The Hackers Notebook
Dynamic blocks are Terraform’s looping mechanism inside resources, letting you generate repeated nested configurations programmatically. They reduce duplication, improve flexibility, and keep your code clean.
