TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Resources & Meta-Arguments

Resources & Meta-Arguments

A resource block declares one object the tool should create and then keep in line with the code: a VPC, a DNS record, a file. Its address is <type>.<name> (aws_vpc.main); the arguments in the body come from the provider's schema, documented per resource on the registry ("Argument Reference" and "Attribute Reference").

hcl
resource "aws_vpc" "main" {               # address: aws_vpc.main
  cidr_block           = "10.0.0.0/16"    # arguments: what you set
  enable_dns_hostnames = true
}
# attributes: what you can read afterwards, e.g. aws_vpc.main.id, aws_vpc.main.arn

Update in place or replace?

When an argument changes, the provider decides how to apply it. Some arguments can be changed on the live object (a tag, an instance size); others force replacement: the old object is destroyed and a new one created (a VPC's CIDR block, an RDS instance's engine, a file's content in the local provider). Replacement is where outages and data loss come from, so learn to spot it in a plan:

bash · try it yourself
mkdir r && cd r
cat > main.tf <<'HCL'
variable "release" {
  type    = string
  default = "1.0.0"
}

resource "terraform_data" "release" {
  input = var.release                        # input can change in place
}

resource "local_file" "config" {
  filename = "app.conf"
  content  = "release=${var.release}\n"      # every local_file argument forces a new file
  lifecycle {
    create_before_destroy = true
  }
}

resource "terraform_data" "cache_warmup" {
  input = "warm the cache"
  lifecycle {
    replace_triggered_by = [terraform_data.release]
  }
}
HCL
tofu init >/dev/null
tofu apply -auto-approve >/dev/null
tofu plan -var release=1.1.0 | grep -v -E 'content_(md5|sha|base64)|Refreshing state'

OpenTofu used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  ~ update in-place (current -> planned)
-/+ destroy and then create replacement
+/- create replacement and then destroy

OpenTofu will perform the following actions:

  # local_file.config must be replaced
+/- resource "local_file" "config" {
      ~ content              = <<-EOT # forces replacement
          - release=1.0.0
          + release=1.1.0
        EOT
      ~ id                   = "8206ac49c697be3da821e8868ac567429af95dfc" -> (known after apply)
        # (3 unchanged attributes hidden)
    }

  # terraform_data.cache_warmup will be replaced due to changes in replace_triggered_by
-/+ resource "terraform_data" "cache_warmup" {
      ~ id     = "05ce61a3-304a-c1ea-d111-b067186e2b58" -> (known after apply)
      ~ output = "warm the cache" -> (known after apply)
        # (1 unchanged attribute hidden)
    }

  # terraform_data.release will be updated in-place
  ~ resource "terraform_data" "release" {
        id     = "22a2212d-66c1-a445-0fa0-dc7cd2714435"
      ~ input  = "1.0.0" -> "1.1.0"
      ~ output = "1.0.0" -> (known after apply)
    }

Plan: 2 to add, 1 to change, 2 to destroy.

─────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so OpenTofu can't
guarantee to take exactly these actions if you run "tofu apply" now.
Symbol Meaning
+ create
~ update in place: the object stays, an attribute changes
-/+ replace: destroy first, then create (the default)
+/- replace, but create the new object first (create_before_destroy)
- destroy
<= read a data source during apply

# forces replacement marks the argument responsible. In a pull-request review, every -/+ on a database, a volume or a load balancer deserves a question.

The meta-arguments

Arguments every resource accepts, whatever its type:

Meta-argument Purpose Lesson
depends_on = [ … ] an ordering dependency the tool can't see from references Dependency Graph
count = N N instances, addressed x[0], x[1] count
for_each = map or set one instance per key, addressed x["key"] for_each
provider = aws.us a non-default provider configuration Providers
lifecycle { } change how create, update and destroy happen below

lifecycle

Setting Effect Typical use
create_before_destroy = true on replacement, create the new object first, then destroy the old one (+/-) load balancer target groups, launch templates, certificates; needs names that can coexist (name_prefix)
prevent_destroy = true any plan that would destroy this object fails production databases, state buckets, KMS keys
ignore_changes = [tags, desired_count] ignore differences in these arguments after creation values another system manages (an autoscaler, a tagging policy)
replace_triggered_by = [ref] replace this resource when the referenced one changes restart a "deployment" resource when its config changes
precondition { } / postcondition { } assert a condition before/after, with an error message guard assumptions (see Variables)

prevent_destroy stops a replacement just as it stops destroy, which is the point:

bash · try it yourself
mkdir guard && cd guard
cat > main.tf <<'HCL'
resource "local_file" "ledger" {
  filename = "ledger.db"
  content  = "important data\n"
  lifecycle {
    prevent_destroy = true
  }
}
HCL
tofu init >/dev/null
tofu apply -auto-approve >/dev/null
sed -i 's/important data/changed data/' main.tf
tofu plan >/dev/null; echo "exit=$?"

Error: Resource instance cannot be destroyed

  on main.tf line 1:
   1: resource "local_file" "ledger" {

Resource instance local_file.ledger has prevent_destroy set, but the plan
calls for it to be destroyed.

To proceed, either disable prevent_destroy for this resource or exclude
instances of this resource from this round using:
    -exclude="local_file.ledger"
exit=1

The guard lives in the code, so it can be removed by editing the code: that edit is visible in review, which is the protection. The OpenTofu message suggests -exclude, an OpenTofu-only flag (OpenTofu).

Tip: Don't reach for ignore_changes = all to silence a noisy plan. Find out what is changing the object outside your code (see Drift & Refresh).

Test yourself

A plan line reads -/+ resource "aws_db_instance" "main". What will happen?

  1. The database is updated in place
  2. The database is destroyed and a new one is created
  3. Only the tags change
  4. Nothing until you run refresh

Which lifecycle setting makes a replacement create the new object before deleting the old one?

  1. prevent_destroy
  2. ignore_changes
  3. create_before_destroy
  4. replace_triggered_by

An autoscaler changes desired_count on a service you manage in code, so every plan wants to reset it. What fits best?

  1. prevent_destroy = true
  2. ignore_changes = [desired_count]
  3. Delete the resource from the code
  4. depends_on on the autoscaler