GuidesTerraform Cost Optimization for AWS - Reduce Your Cloud Bill
Practical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity.
Guides
How to use Terraform dynamic blocks to generate repeated nested blocks from variables and data.

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:
GuidesPractical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity.
GuidesHow to achieve zero-downtime deployments with Terraform using blue-green, rolling updates, and create_before_destroy.
GuidesComplete guide to testing Terraform configurations with terraform test, Terratest, and validation rules.
GuidesComplete guide to Terraform data sources: querying existing infrastructure, filtering, and common patterns.