Terraform count vs for_each - When to Use Each (With Examples)
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...
Guides
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 ...
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.
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"] },
]
}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
}
}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
}
}
}
}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/"
}
}Good use cases:
Avoid when:
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...
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...