depends_on, provider and lifecycle
You have met count and for_each. Three more meta-arguments finish the set. Each solves a specific problem that references alone cannot, and each is easy to overuse.
The rule
depends_on for hidden order, provider for which one, lifecycle for how it lives and dies.
depends_on adds an ordering Terraform cannot see. Normally references create dependencies. But suppose Crumb's server runs a start-up script that downloads files from the assets bucket by a fixed name: nothing in the block refers to the bucket, so Terraform might build them in parallel.
resource "aws_instance" "web" {
ami = "ami-0123456789abcdef0"
instance_type = "t3.micro"
user_data = file("start.sh")
depends_on = [aws_s3_bucket.assets]
}It takes a list of addresses, not attribute values. Prefer a real reference when one exists.
provider picks a non-default provider configuration, such as provider = aws.virginia from the providers section.
lifecycle is a nested block that changes the resource's life:
resource "aws_instance" "web" {
# ...
lifecycle {
create_before_destroy = true
ignore_changes = [tags]
}
}
resource "aws_s3_bucket" "assets" {
bucket = "crumb-prod-assets"
lifecycle {
prevent_destroy = true
}
}create_before_destroy— on replacement, build the new object first, then remove the old (+/-).prevent_destroy— any plan that would destroy this object fails with an error. It protects only while the line is in the configuration; delete the block and the protection goes with it.ignore_changes— listed arguments are not compared after creation, so edits made outside Terraform are left alone.replace_triggered_by— replace this resource whenever a referenced resource or attribute changes.
The shortcut
Match the worry to the tool: "wrong order?" depends_on. "wrong account or region?" provider. "downtime, accident or outside edits?" lifecycle.
Downtime on replacement
The worry is how it dies.
create_before_destroy = trueon the web server.
The trap: sprinkling depends_on everywhere "to be safe". It makes plans slower and more cautious, and it hides the real relationships that references would show.
Drills
Answer fast — trust the rule.
When is depends_on the right tool?
A plan would destroy a bucket that has prevent_destroy = true. What happens?
Which setting stops Terraform undoing tag edits made by another tool?
You delete a resource block that had prevent_destroy = true. What does the next plan do?
Remember
- depends_on: hidden order. provider: which configuration. lifecycle: how it is replaced, protected or compared.
- Shortcut: order, account, or life-and-death? Pick the matching tool.
- Trap: overusing depends_on, and trusting prevent_destroy after the block is gone.
