Terraform Dynamic Blocks - Complete Guide With Examples
How to use Terraform dynamic blocks to generate repeated nested blocks from variables and data. Step-by-step guide with code examples and best practices for ...
Guides
Complete comparison of Terraform count vs for_each with examples, use cases, and best practices. Step-by-step guide with code examples and best practices for...
Both count and for_each create multiple instances of a resource, but they behave differently and have different use cases.
| Feature | count | for_each |
|---|---|---|
| Index type | Numeric (0, 1, 2...) | String key |
| Reordering | Causes recreation | Safe |
| Conditional | count = var.enabled ? 1 : 0 | N/A |
| Best for | Simple on/off, identical copies | Distinct items with unique keys |
Creating identical copies or toggling resources on/off:
resource "aws_instance" "web" {
count = var.instance_count
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "web-${count.index}"
}
}Conditionally creating a resource:
resource "aws_cloudwatch_metric_alarm" "high_cpu" {
count = var.enable_monitoring ? 1 : 0
# ... alarm configuration
}Creating resources from a map or set with meaningful keys:
resource "aws_iam_user" "team" {
for_each = toset(["alice", "bob", "charlie"])
name = each.value
}Resources identified by name rather than index:
variable "buckets" {
default = {
logs = { acl = "log-delivery-write" }
assets = { acl = "private" }
backups = { acl = "private" }
}
}
resource "aws_s3_bucket" "this" {
for_each = var.buckets
bucket = "${var.project}-${each.key}"
}With count, removing an item from the middle of a list causes all subsequent resources to be recreated:
# count = ["a", "b", "c"] → remove "b" → "c" shifts to index 1 → RECREATEDWith for_each, each resource is keyed by name, so removing one doesn't affect others.
for_each keys must be known at plan time. This fails:
# ERROR: for_each depends on resource that hasn't been created yet
resource "aws_subnet" "this" {
for_each = toset(aws_availability_zones.available.names) # Unknown at plan!
}Fix: Use a data source or variable instead.
How to use Terraform dynamic blocks to generate repeated nested blocks from variables and data. Step-by-step guide with code examples and best practices for ...
Practical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity. Step-by-step guide with code examples and ...
How to achieve zero-downtime deployments with Terraform using blue-green, rolling updates, and create_before_destroy. Step-by-step guide with code examples a...
Complete guide to testing Terraform configurations with terraform test, Terratest, and validation rules. Step-by-step guide with code examples and best pract...