count vs. for_each
count |
for_each |
|
|---|---|---|
| Input | Whole number | Map, or set of strings |
| Instance address | res[0], res[1] |
res["alice"] |
| Iteration values | count.index |
each.key, each.value (equal for sets) |
| Removing a middle item | Shifts indexes, so later instances are updated or replaced | Only that key is destroyed |
| Best for | N identical copies, conditional creation (? 1 : 0) |
Distinct, named instances |
Rules:
- You can't use
countandfor_eachon the same block. for_eachkeys must be known at plan time, so they can't come from attributes that are only known after apply.for_eachdoesn't accept a list directly. Wrap it withtoset().
Implicit vs. explicit dependencies
- Implicit: a reference such as
image = docker_image.nginx.image_id. This is the preferred form. - Explicit:
depends_ondeclares a dependency Terraform can't see from references. A typical case: an application needs an IAM policy to exist before it starts, but it never references the policy.
resource "local_file" "app_config" {
filename = "${path.module}/app.conf"
content = "ready = true\n"
depends_on = [terraform_data.bootstrap] # list of whole resources or modules, not attributes
}depends_on rules:
- It must be a static list of references to resources, data sources, or modules. It can't contain attribute paths or expressions.
- On a
moduleblock, it makes every object in the module wait. - On a data source, it defers the read to apply when the dependency has pending changes, which can produce more
(known after apply)values. - Use it as a last resort, and add a comment explaining why.
provider meta-argument
provider = aws.west selects an aliased configuration (Module 2).
lifecycle
| Argument | Effect | Notes |
|---|---|---|
create_before_destroy = true |
When replacing, create the new object first, then destroy the old one (+/-) |
Fails if names must be unique and can't coexist |
prevent_destroy = true |
Any plan that would destroy this object errors | Doesn't protect it if you delete the block from config |
ignore_changes = [attr, ...] or all |
Ignore differences in those attributes when planning updates | For attributes that other systems manage |
replace_triggered_by = [ref, ...] |
Replace this resource when a referenced resource or attribute changes | References must be managed resources or their attributes. To trigger on a variable, route it through terraform_data. |
precondition / postcondition |
Custom checks | Lesson 4.7 |