# Resources: count, for_each and lifecycle

How Terraform decides to create, update, replace or destroy, how to make many resources with count and for_each (and why for_each is usually safer), and how lifecycle rules protect what matters.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 5. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/05-resources

## What you will learn

- Read a plan and name each action from its symbol
- Explain why some changes update in place and others force a replacement
- Create many resources with count and for_each, and explain the index-shift problem
- Use lifecycle settings such as prevent_destroy, create_before_destroy and ignore_changes
- Know when depends_on is needed and when it isn't

> **Lab status.** **Verified lab:** the for_each and count plans, the count-vs-for_each comparison, prevent_destroy and the duplicate-name error. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** the AWS depends_on example and create_before_destroy: explained, not run. <br />**Cloud lab:** depends_on with IAM needs an AWS account.

A **resource** is one thing Terraform manages: a file, a server, a DNS record. This lesson is about
how Terraform decides what to do with each one on every run, how to create many from one block, and
how to stop it from deleting the things you can't afford to lose.

## Resource behaviour

> **Figure.** Left: a dependency graph. random_pet.server is referenced by local_file.inventory, so it is created first; local_file.worker zero is independent and runs in parallel; local_file.summary depends on both. Right: the plan actions and their symbols: plus create for a new resource, tilde update in place when an argument can change live, minus slash plus replace when an argument forces replacement, minus destroy when removed from config, and less-than equals read for a data source.
>
> References order the work; the symbol in front of each resource tells you what will happen to it.

On each plan, Terraform compares three things for every resource: your configuration, the state
(what it created last time) and the real object (refreshed through the provider). Then it picks one
action:

| Symbol | Action          | When                                                              |
| ------ | --------------- | ----------------------------------------------------------------- |
| `+`    | create          | In the config, not in state                                       |
| `~`    | update in place | An argument changed, and the API can change it on the live object |
| `-/+`  | replace         | An argument changed that the API **can't** change in place        |
| `-`    | destroy         | In state, no longer in the config                                 |
| `<=`   | read            | A data source (lesson 11)                                         |

Whether a change is an update or a replace isn't up to you: the provider decides. In the plan,
Terraform marks the argument that caused it with `# forces replacement`:

```text
  # local_file.inventory must be replaced
-/+ resource "local_file" "inventory" {
      ~ content              = <<-EOT
            server: model-kiwi
        EOT -> (known after apply) # forces replacement
```

For `local_file`, any content change replaces the file. For an EC2 instance, changing the
`instance_type` updates in place (with a stop and start), while changing the `ami` replaces it, and
the old server and its local disk are gone. Always find out why a `-/+` happens before you approve
it.

## count and for each

Two **meta-arguments** (they work on any resource type) create several resources from one block.

### count: N copies by position

```hcl
resource "local_file" "worker" {
  count = var.replicas # 0 means none: a common on/off switch

  filename = "${path.module}/out/${local.prefix}-worker-${count.index}.txt"
  content  = local.common
}
```

Inside the block, `count.index` is 0, 1, 2... The resources are addressed `local_file.worker[0]`,
`local_file.worker[1]` and so on.

### for_each: one per key

```hcl
variable "servers" {
  type = map(string)
  default = {
    web = "t3.micro"
    api = "t3.small"
  }
}

resource "local_file" "server" {
  for_each = var.servers

  filename = "${path.module}/out/${local.prefix}-${each.key}.txt"
  content  = "${local.common}size: ${each.value}\n"
}
```

`for_each` takes a **map** or a **set of strings**. Inside, `each.key` and `each.value` are the
current entry, and the resources are addressed by key: `local_file.server["web"]`. From the lab's
plan:

```text
  # local_file.server["api"] will be created
  + resource "local_file" "server" {
      + content              = <<-EOT
            managed-by: terraform
            env: dev
            size: t3.small
        EOT
      + filename             = "./out/shop-dev-api.txt"
```

### Why for_each is usually safer

The same three users, once with `count` and once with `for_each`. Then remove the **first** user:

```hcl
variable "users" {
  type    = list(string)
  default = ["asha", "ravi", "meera"]
}

resource "local_file" "by_count" {
  count    = length(var.users)
  filename = "${path.module}/out/count-${count.index}.txt"
  content  = var.users[count.index]
}

resource "local_file" "by_each" {
  for_each = toset(var.users)
  filename = "${path.module}/out/each-${each.key}.txt"
  content  = each.key
}
```

The real plan with `users = ["ravi", "meera"]`, trimmed to the important lines:

```text
  # local_file.by_count[0] must be replaced
      ~ content              = "asha" -> "ravi" # forces replacement
  # local_file.by_count[1] must be replaced
      ~ content              = "ravi" -> "meera" # forces replacement
  # local_file.by_count[2] will be destroyed
  # (because index [2] is out of range for count)
  # local_file.by_each["asha"] will be destroyed
  # (because key ["asha"] is not in for_each map)

Plan: 2 to add, 0 to change, 4 to destroy.
```

With `count`, Ravi moved from index 1 to 0 and Meera from 2 to 1, so **both** are replaced, and
index 2 is destroyed: three resources touched to remove one person. With `for_each`, only `asha` is
destroyed. On real infrastructure, `count` would have replaced two healthy servers.

**Rule:** use `count` for "N identical things" or a 0/1 switch. Use `for_each` whenever items have
identities (names, regions, users).

## Lifecycle

The `lifecycle` block changes how Terraform handles one resource:

| Setting                        | What it does                                               | Typical use                                                               |
| ------------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------------------- |
| `prevent_destroy = true`       | Any plan that would destroy it fails                       | Databases, state buckets, DNS zones                                       |
| `create_before_destroy = true` | On replace, create the new one first, then destroy the old | Anything behind a load balancer, certificates                             |
| `ignore_changes = [tags]`      | Ignore drift in these arguments                            | Values changed by another system, like an autoscaler's `desired_capacity` |
| `replace_triggered_by = [...]` | Replace this when another resource changes                 | Restart a service when its config changes                                 |

Here's `prevent_destroy` stopping a real `terraform destroy`:

```hcl
resource "local_file" "database" {
  filename = "${path.module}/out/${local.prefix}-database.txt"
  content  = "do not delete\n"

  lifecycle {
    prevent_destroy = true
  }
}
```

```text
$ terraform destroy -auto-approve -var-file=dev.tfvars

Error: Instance cannot be destroyed

  on main.tf line 34:
  34: resource "local_file" "database" {

Resource local_file.database has lifecycle.prevent_destroy set, but the plan
calls for this resource to be destroyed. To avoid this error and continue
with the plan, either disable lifecycle.prevent_destroy or reduce the scope
of the plan using the -target option.
```

The whole destroy stopped, not just that one file. That's the point: it forces a human to edit the
code and explain why in a pull request.

Without `create_before_destroy`, a replace destroys first and creates second, which means downtime.
With it, the new object comes up first. It needs names that can briefly exist twice, which is why
many AWS resources offer `name_prefix` instead of a fixed `name`.

## Explicit dependencies

Most of the time references order the graph for you. `depends_on` is for a dependency Terraform
can't see. The classic case: an EC2 instance whose startup script reads from S3 needs the IAM policy
attached first, but nothing in the instance's arguments refers to the policy attachment.

```hcl
resource "aws_instance" "app" {
  ami                  = data.aws_ami.ubuntu.id
  instance_type        = "t3.micro"
  iam_instance_profile = aws_iam_instance_profile.app.name

  depends_on = [aws_iam_role_policy_attachment.read_s3]
}
```

Use it sparingly. Every `depends_on` makes Terraform more cautious and plans less precise, and a
missing reference is often the better fix.

> **In production.** Read every `-/+` and `-` in a plan before approving it, and ask why. Put `prevent_destroy` on stateful resources, and turn on the cloud's own deletion protection too (for example `deletion_protection = true` on RDS), since lifecycle rules only protect against Terraform.

## When it goes wrong

**Two resources with the same address.** Copy-pasting a block and forgetting to rename it:

```text
$ terraform validate

Error: Duplicate resource "local_file" configuration

  on main.tf line 19:
  19: resource "local_file" "note" {

A local_file resource named "note" was already declared at main.tf:13,1-29.
Resource names must be unique per type in each module.
```

_Fix:_ give the copy its own name. If it should be several of the same thing, use `for_each`.

**An unexpected replacement in the plan.** You changed one argument and the plan shows `-/+`. Find the
line marked `# forces replacement`: that argument can't change in place. Decide before applying:
accept the replacement (with `create_before_destroy` to avoid downtime), revert the change, or, if
only the name in your code changed, use a `moved` block (lesson 8) instead.

**prevent_destroy blocks a run you meant.** The error names the resource. Remove `prevent_destroy` in
a reviewed change, apply, and put it back if the resource should stay protected. Never work around it
with `-target` on production without a second person agreeing.

## Mission: See the count index shift yourself

Create the by_count and by_each resources from this lesson with three users, apply, then plan with the first user removed. Write down how many resources each approach would destroy and replace, and which approach you'd use for servers.

- You'll have: ~/count-vs-foreach.txt

```sh
$ terraform apply -auto-approve
$ terraform plan -var='users=["ravi","meera"]' -no-color | grep -E '# local_file|Plan:' > ~/count-vs-foreach.txt
$ cat ~/count-vs-foreach.txt
```

The lab's plan was `2 to add, 0 to change, 4 to destroy`: count replaced two files and destroyed
one, for_each destroyed only `asha`. For servers, users or anything with a name, use for_each.

## Try it

- Create two files with count, then remove the first name from the list and read the plan.
- Do the same with for_each over a set and compare the plans.
- Add `prevent_destroy = true` to a resource and run `terraform destroy`.
- Change a resource's `content` and find the words "forces replacement" in the plan.
- Do the mini mission and keep `~/count-vs-foreach.txt`.

## Quiz

1. A plan shows `-/+` next to a resource. What will happen?
   - It will be updated in place
   - **It will be destroyed and a new one created, because an argument can't change in place** (answer)
   - Nothing
   Why: -/+ means replace. For a server or database that means a new resource, often with data loss or downtime, so always read why ("forces replacement").

2. A list of three users is used with count. You remove the first user. What happens?
   - Only the first user's resource is destroyed
   - **Every later resource shifts down one index, so they are changed or replaced, and the last index is destroyed** (answer)
   - Terraform refuses to plan
   Why: count addresses resources by position. Removing an item moves every later item to a new index. for_each addresses by key, so only the removed key is destroyed.

3. What does `prevent_destroy = true` do?
   - It makes the resource impossible to change
   - **Terraform errors out of any plan that would destroy that resource** (answer)
   - It deletes the resource from state
   Why: It's a safety catch for databases and buckets. It doesn't stop changes in place, and someone can still remove the line, so it guards against accidents, not intent.

4. When do you need depends_on?
   - On every resource
   - **Only when there is a dependency Terraform can't see from references, such as an IAM policy that must exist before an app starts** (answer)
   - Never
   Why: References already order the graph. depends_on is for hidden dependencies, and overusing it makes plans slower and less precise.

## Resources

- [Resource behaviour](https://developer.hashicorp.com/terraform/language/resources/behavior) (HashiCorp)
- [The count meta-argument](https://developer.hashicorp.com/terraform/language/meta-arguments/count) (HashiCorp)
- [The for_each meta-argument](https://developer.hashicorp.com/terraform/language/meta-arguments/for_each) (HashiCorp)
- [The lifecycle meta-argument](https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle) (HashiCorp)
- [The depends_on meta-argument](https://developer.hashicorp.com/terraform/language/meta-arguments/depends_on) (HashiCorp)
