Terraform · Lesson 5 of 12 · 4 min read
Meta-arguments and lifecycle
count vs for_each
# count — indexed list
resource "aws_iam_user" "dev" {
count = length(var.developers) # ["asha", "bala", "chitra"]
name = var.developers[count.index]
}
# addresses: aws_iam_user.dev[0], [1], [2]
# for_each — keyed by map keys or set values
resource "aws_iam_user" "dev" {
for_each = toset(var.developers)
name = each.value
}
# addresses: aws_iam_user.dev["asha"], ["bala"], ["chitra"]
The count index problem: remove "asha" from the list and with count every later element shifts index — Terraform sees [0] changed from asha to bala, [1] from bala to chitra, and [2] deleted: it modifies or recreates resources you didn't touch. With for_each, removing "asha" deletes only dev["asha"].
Rules of thumb:
- for_each for collections of distinct things (subnets, users, buckets, services).
- count for "zero or one" conditional creation, or truly identical copies.
resource "aws_cloudwatch_log_group" "flow_logs" {
count = var.enable_flow_logs ? 1 : 0
name = "/vpc/${local.name_prefix}/flow-logs"
}
# reference: aws_cloudwatch_log_group.flow_logs[0].arn (or one(aws_cloudwatch_log_group.flow_logs[*].arn))
Subnets from a map of objects:
variable "private_subnets" {
default = {
a = { cidr = "10.20.0.0/19", az = "ap-south-1a" }
b = { cidr = "10.20.32.0/19", az = "ap-south-1b" }
c = { cidr = "10.20.64.0/19", az = "ap-south-1c" }
}
}
resource "aws_subnet" "private" {
for_each = var.private_subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value.cidr
availability_zone = each.value.az
tags = { Name = "${local.name_prefix}-private-${each.key}", "kubernetes.io/role/internal-elb" = "1" }
}
for_each keys must be known at plan time — you can't key on an attribute only known after apply (like a generated ID); you'll get "Invalid for_each argument". Use static keys (names) instead.
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
lifecycle
resource "aws_db_instance" "orders" {
# ...
deletion_protection = true # AWS-side protection too
lifecycle {
prevent_destroy = true # plan errors if anything would destroy it
create_before_destroy = false
ignore_changes = [password] # managed elsewhere / rotated
}
}
resource "aws_launch_template" "nodes" {
lifecycle { create_before_destroy = true } # new one exists before old is removed
}
resource "aws_autoscaling_group" "web" {
lifecycle {
ignore_changes = [desired_capacity] # the autoscaler changes this
replace_triggered_by = [aws_launch_template.nodes.latest_version]
}
}
- prevent_destroy — guardrail for critical resources (databases, state buckets, hosted zones). Combine with provider-side deletion protection.
- create_before_destroy — for replacements that must not cause downtime (certificates, launch templates, security groups attached elsewhere). Names must be unique-able (use
name_prefix). - ignore_changes — attributes another system manages (tags from a tagging tool, ASG desired capacity, Kubernetes-managed annotations).
- replace_triggered_by — force replacement when something else changes.
- precondition / postcondition blocks validate assumptions with custom error messages.
Forcing a single replacement:
terraform apply -replace="aws_instance.bastion" # modern replacement for `terraform taint`
terraform plan -target=module.vpc # limit scope — emergencies only; leaves config and state out of sync
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
depends_on
Use only for dependencies Terraform can't see through references:
resource "aws_lambda_function" "processor" {
# ...
depends_on = [aws_iam_role_policy_attachment.processor_logs]
}