Data Sources, Dependencies, and Lifecycle Rules

Read existing infrastructure with data sources, control ordering with references and depends_on, and guard risky changes with lifecycle rules, conditions and -replace.

By The Dark DebuggerUpdated 25 min read

This tutorial covers how a configuration reads things it doesn't manage (data sources), how Terraform decides the order of operations (the dependency graph and depends_on), and the rules you attach to resources for the risky moments (lifecycle, preconditions and postconditions, and -replace). It assumes you're comfortable with Providers and Resources, in particular reading ~, -/+ and +/- in a plan. Everything runs locally; a small Python web server stands in for an internal artifact server, and the AWS data sources are validated and planned with honest notes about what that can and can't show.

Why this matters

A deployment configuration rarely lives alone. The checkout service's deploy step needs the release version that CI published a few minutes ago, the subnets the network team created in a different Terraform configuration, and the office IP ranges the security team keeps in a file. Terraform doesn't own any of those, but it has to read them, and it has to read them before it plans anything that depends on them.

The same configuration also contains things that must be handled carefully: a database that must never be deleted by accident, a certificate that must never be missing, a token that should rotate on every release. Getting those wrong doesn't produce an error message. It produces an outage. This tutorial is about making Terraform read the world correctly and refuse to do the dangerous thing.

Data sources: reading what you don't manage

A data source is declared with a data block instead of resource. Terraform reads it, usually during plan, and never creates, changes or deletes the thing behind it. You reference its attributes as data.TYPE.NAME.ATTRIBUTE.

resourcedata
PurposeManage an object's whole lifecycleRead an existing object or value
Addresslocal_file.deploy_envdata.local_file.office_cidrs
When Terraform talks to itCreate, update, delete during applyRead on every plan and apply
Removing the blockDestroys the objectJust stops reading it

Here is the deploy project. It reads two things, a file in the repository and a JSON manifest over HTTP, and writes two files from them:

terraform {
  required_version = ">= 1.6"
 
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
    http = {
      source  = "hashicorp/http"
      version = "~> 3.4"
    }
  }
}
 
variable "artifact_server" {
  description = "Base URL of the internal artifact server"
  type        = string
  default     = "http://127.0.0.1:8731"
}
 
# A file kept in the repository by the security team.
data "local_file" "office_cidrs" {
  filename = "${path.module}/office-cidrs.txt"
}
 
# The release manifest published by CI.
data "http" "release" {
  url = "${var.artifact_server}/releases/checkout/latest.json"
 
  request_headers = {
    Accept = "application/json"
  }
 
  lifecycle {
    postcondition {
      condition     = self.status_code == 200
      error_message = "Release manifest request returned HTTP ${self.status_code}."
    }
  }
}
 
locals {
  release      = jsondecode(data.http.release.response_body)
  office_cidrs = compact(split("\n", data.local_file.office_cidrs.content))
}
 
resource "local_file" "nginx_allow" {
  filename        = "${path.module}/out/allow-office.conf"
  file_permission = "0644"
  content         = join("", [for cidr in local.office_cidrs : "allow ${cidr};\n"])
}
 
resource "local_file" "deploy_env" {
  filename        = "${path.module}/out/deploy.env"
  file_permission = "0644"
  content         = <<-EOT
    APP_VERSION=${local.release.version}
    ARTIFACT_URL=${var.artifact_server}/releases/checkout/${local.release.artifact}
    ARTIFACT_SHA256=${local.release.sha256}
  EOT
 
  lifecycle {
    precondition {
      condition     = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+$", local.release.version))
      error_message = "Release version \"${local.release.version}\" is not of the form MAJOR.MINOR.PATCH."
    }
  }
}
 
output "release_version" {
  value = local.release.version
}

The inputs it reads look like this. office-cidrs.txt:

203.0.113.0/24
198.51.100.17/32

And the manifest the artifact server returns for releases/checkout/latest.json (I served a directory with python3 -m http.server 8731 --bind 127.0.0.1 and computed the checksum from a real tarball):

{
  "version": "2.14.1",
  "artifact": "checkout-2.14.1.tar.gz",
  "sha256": "bedeae963d65f312a01b23d6f4a6316473d91365a224460861e47dfa64f81ccc",
  "published": "2026-11-09T18:20:00Z"
}

Ignore the lifecycle blocks for now; they're covered further down.

terraform plan
data.local_file.office_cidrs: Reading...
data.local_file.office_cidrs: Read complete after 0s [id=53e2c735c5c41d8488fe5d095d6f9293b2f27f85]
data.http.release: Reading...
data.http.release: Read complete after 0s [id=http://127.0.0.1:8731/releases/checkout/latest.json]
 
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create
 
Terraform will perform the following actions:
 
  # local_file.deploy_env will be created
  + resource "local_file" "deploy_env" {
      + content              = <<-EOT
            APP_VERSION=2.14.1
            ARTIFACT_URL=http://127.0.0.1:8731/releases/checkout/checkout-2.14.1.tar.gz
            ARTIFACT_SHA256=bedeae963d65f312a01b23d6f4a6316473d91365a224460861e47dfa64f81ccc
        EOT
[…]
  # local_file.nginx_allow will be created
  + resource "local_file" "nginx_allow" {
      + content              = <<-EOT
            allow 203.0.113.0/24;
            allow 198.51.100.17/32;
        EOT
[…]
Plan: 2 to add, 0 to change, 0 to destroy.
 
Changes to Outputs:
  + release_version = "2.14.1"

The Reading... lines come first: Terraform resolved both data sources before planning, so the plan already contains the real version and checksum. That's the value of data sources: the reviewer sees APP_VERSION=2.14.1, not (known after apply).

Data sources are read on every run. The web server's access log after one plan and one apply:

127.0.0.1 - - [09/Nov/2026 22:03:47] "GET /releases/checkout/latest.json HTTP/1.1" 200 -
127.0.0.1 - - [09/Nov/2026 22:03:48] "GET /releases/checkout/latest.json HTTP/1.1" 200 -

So when CI publishes 2.15.0, the next plan picks it up with no change to the configuration. It also means a slow or flaky endpoint slows down or breaks every plan, which is why the http data source has that postcondition.

Reading another configuration's outputs

Large estates are split into several configurations, each with its own state: the network team owns VPCs and subnets, application teams own their services. The terraform_remote_state data source reads another configuration's outputs. To keep it local, network/ is a stand-in for the network team's configuration:

terraform {
  required_version = ">= 1.6"
}
 
locals {
  vpc_cidr = "10.20.0.0/16"
}
 
# Stands in for the VPC and subnets the network team manages.
resource "terraform_data" "network" {
  input = {
    vpc_cidr        = local.vpc_cidr
    private_subnets = [for i in range(3) : cidrsubnet(local.vpc_cidr, 8, i)]
  }
}
 
output "vpc_cidr" {
  value = terraform_data.network.output.vpc_cidr
}
 
output "private_subnets" {
  value = terraform_data.network.output.private_subnets
}
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
Outputs:
 
private_subnets = [
  "10.20.0.0/24",
  "10.20.1.0/24",
  "10.20.2.0/24",
]
vpc_cidr = "10.20.0.0/16"

The deploy project reads it with a new file, network.tf:

# Read the outputs of the network team's configuration.
data "terraform_remote_state" "network" {
  backend = "local"
 
  config = {
    path = "${path.module}/../network/terraform.tfstate"
  }
}
 
resource "local_file" "subnets" {
  filename        = "${path.module}/out/subnets.txt"
  file_permission = "0644"
  content         = "${join("\n", data.terraform_remote_state.network.outputs.private_subnets)}\n"
}
terraform apply -auto-approve
cat out/subnets.txt
data.terraform_remote_state.network: Reading...
data.terraform_remote_state.network: Read complete after 0s
[…]
local_file.subnets: Creating...
local_file.subnets: Creation complete after 0s [id=e089a6f93550f5acb67e4853d8d085c27baa9a67]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
10.20.0.0/24
10.20.1.0/24
10.20.2.0/24

In a real team the backend would be s3, gcs, azurerm or HCP Terraform rather than local, but the shape is the same (backends are covered in Terraform State). One caution: reading remote state requires read access to the whole state file of the other configuration, secrets included, and it couples you to that configuration's output names. Many teams prefer to publish the handful of values others need somewhere narrower, such as a parameter store, and read that with an ordinary data source.

Cloud data sources: AWS

On AWS, the two data sources you'll meet first are aws_caller_identity (which account and role is this run using?) and aws_ami (the newest image matching a filter):

# Which account and identity is this run using?
data "aws_caller_identity" "current" {}
 
# The newest Ubuntu 24.04 image published by Canonical.
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"] # Canonical
 
  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
  }
}
 
resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
 
  tags = {
    Name       = "checkout-web"
    created_by = data.aws_caller_identity.current.arn
  }
}

With the AWS provider (~> 6.0, region us-east-1) declared, this passes terraform validate. Here's where I have to be honest about the limits of testing without an account. The mock-credential trick from Providers and Resources works for planning new resources because no API call is needed. Data sources are different: they must call the API during plan. With fake keys, AWS rejected both calls:

data.aws_caller_identity.current: Reading...
data.aws_ami.ubuntu: Reading...
 
Planning failed. Terraform encountered an error while generating this plan.
 
╷
│ Error: reading STS Caller Identity
│ 
│   with data.aws_caller_identity.current,
│   on main.tf line 15, in data "aws_caller_identity" "current":
│   15: data "aws_caller_identity" "current" {}
│ 
│ operation error STS: GetCallerIdentity, https response error StatusCode:
│ 403, RequestID: bab39c24-b25f-4f4b-9c38-e73fb6994b44, api error
│ InvalidClientTokenId: The security token included in the request is
│ invalid.
╵
[…]

With real credentials the plan would show the AMI ID that aws_ami found, which brings up a judgment call. most_recent = true means a new Canonical image tomorrow changes the plan, and because an instance's ami can't change in place, the next apply replaces the server. That's sometimes what you want (always build on the latest patched image) and often not (production should change images deliberately). Teams that want control pin the AMI ID in a variable, or use ignore_changes, covered below.

Implicit dependencies and the graph

Everything in the deploy project is ordered by references, as you saw in Providers and Resources. terraform graph prints the dependency graph in Graphviz DOT format:

terraform graph
digraph G {
  rankdir = "RL";
  node [shape = rect, fontname = "sans-serif"];
  "data.http.release" [label="data.http.release"];
  "data.local_file.office_cidrs" [label="data.local_file.office_cidrs"];
  "data.terraform_remote_state.network" [label="data.terraform_remote_state.network"];
  "local_file.deploy_env" [label="local_file.deploy_env"];
  "local_file.nginx_allow" [label="local_file.nginx_allow"];
  "local_file.subnets" [label="local_file.subnets"];
  "terraform_data.smoke_test" [label="terraform_data.smoke_test"];
  "local_file.deploy_env" -> "data.http.release";
  "local_file.nginx_allow" -> "data.local_file.office_cidrs";
  "local_file.subnets" -> "data.terraform_remote_state.network";
  "terraform_data.smoke_test" -> "local_file.deploy_env";
}

Each arrow points from a node to something it depends on: deploy_env needs the release manifest, nginx_allow needs the CIDR file. Things with no path between them (the three chains here) run in parallel. If Graphviz is installed, terraform graph | dot -Tsvg > graph.svg draws it; the text is already readable for a graph this size. The last edge, from smoke_test to deploy_env, isn't a reference. It comes from depends_on.

When you need depends_on

Sometimes a dependency is real but invisible to Terraform. The deploy project runs a smoke test after writing deploy.env, using a local-exec provisioner, which runs a shell command after a resource is created:

resource "terraform_data" "smoke_test" {
  # Re-run the check whenever a new release is deployed.
  triggers_replace = [local.release.version]
 
  provisioner "local-exec" {
    command = "grep -q '^APP_VERSION=' out/deploy.env && echo 'deploy.env looks valid'"
  }
 
  # The command reads out/deploy.env by path, so no reference tells
  # Terraform about the dependency. Declare it.
  depends_on = [local_file.deploy_env]
}

The command reads out/deploy.env by path, inside a string. Terraform can't see into shell commands, so without depends_on it would happily run the test in parallel with writing the file. With it:

terraform_data.smoke_test: Creating...
terraform_data.smoke_test: Provisioning with 'local-exec'...
terraform_data.smoke_test (local-exec): Executing: ["/bin/sh" "-c" "grep -q '^APP_VERSION=' out/deploy.env && echo 'deploy.env looks valid'"]
terraform_data.smoke_test (local-exec): deploy.env looks valid
terraform_data.smoke_test: Creation complete after 0s [id=b58d9b86-efa1-2d8c-9c77-62c4d659a1e8]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

That's the legitimate use of depends_on: a dependency that exists only outside the configuration (a script, an IAM permission that must propagate, a service that reads a file by name). Leave a comment saying why, as above, because nobody can infer it from the code. If a reference can express the relationship, use the reference instead: command = "grep -q '^APP_VERSION=' ${local_file.deploy_env.filename}" would have created the same edge and documented itself.

Why an unnecessary depends_on hurts

depends_on is not free, and it's most expensive on data sources. Suppose someone adds a "just to be safe" dependency to the CIDR file:

data "local_file" "office_cidrs" {
  filename = "${path.module}/office-cidrs.txt"
 
  depends_on = [local_file.deploy_env]
}

Then CI publishes release 2.15.0 and the next plan runs:

[…]
  # data.local_file.office_cidrs will be read during apply
  # (depends on a resource or a module with changes pending)
 <= data "local_file" "office_cidrs" {
      + content              = (known after apply)
      + filename             = "./office-cidrs.txt"
      + id                   = (known after apply)
    }
[…]
  # local_file.nginx_allow must be replaced
-/+ resource "local_file" "nginx_allow" {
      ~ content              = <<-EOT
            allow 203.0.113.0/24;
            allow 198.51.100.17/32;
        EOT -> (known after apply) # forces replacement
[…]
Plan: 3 to add, 0 to change, 3 to destroy.

Because deploy_env has changes pending, Terraform can't read the data source until that change is applied, so its content is unknown at plan time. Unknown content "forces replacement" of nginx_allow, a file that isn't changing at all. Without the depends_on, the same release plans just the two resources that really change:

  # local_file.deploy_env must be replaced
  # terraform_data.smoke_test must be replaced
Plan: 2 to add, 0 to change, 2 to destroy.

On real infrastructure, this pattern turns into plans that want to replace load balancers or rewrite IAM policies on every deploy, and reviewers learn to ignore plans, which is worse. A depends_on on a whole module has the same effect on every data source inside it. Add depends_on only for invisible dependencies, and never to a data source "just in case".

lifecycle rules

Every resource accepts a lifecycle block that changes how Terraform treats it during changes. The lifecycle project puts four of them side by side:

# Stands in for a database: losing it would be a very bad day.
resource "terraform_data" "orders_db" {
  input = {
    engine  = "postgres"
    version = "16"
  }
 
  lifecycle {
    prevent_destroy = true
  }
}
 
# The release currently deployed.
resource "terraform_data" "release" {
  input = var.release_version
}
 
# Rotate the API token on every release, even though nothing in the
# token's own arguments changes.
resource "random_password" "api_token" {
  length  = 32
  special = false
 
  lifecycle {
    replace_triggered_by = [terraform_data.release]
  }
}
 
# Deployment metadata; the deploy pipeline rewrites last_deployed itself.
resource "terraform_data" "deploy_marker" {
  input = {
    service       = "checkout"
    last_deployed = "2026-11-09T18:20:00Z"
  }
 
  lifecycle {
    ignore_changes = [input["last_deployed"]]
  }
}
 
# A certificate bundle that must never be missing.
resource "local_file" "tls_bundle" {
  filename        = "${path.module}/out/tls-bundle.pem"
  file_permission = "0644"
  content         = "# certificate serial ${var.cert_serial}\n"
 
  lifecycle {
    create_before_destroy = true
  }
}

(The file also declares the local and random providers and two variables, release_version defaulting to "2.14.1" and cert_serial defaulting to "4f:1a:09:c2".) After an initial apply, here's each rule in action.

create_before_destroy

By default a replacement destroys the old object first. For a certificate, a load balancer or a launch template, that leaves a gap. create_before_destroy = true flips the order, and the plan symbol changes from -/+ to +/-. Rotating the certificate serial:

terraform apply -auto-approve -var release_version=2.15.0 -var cert_serial=7d:22:e1:90
[…]
+/- create replacement and then destroy
 
Terraform will perform the following actions:
 
  # local_file.tls_bundle must be replaced
+/- resource "local_file" "tls_bundle" {
      ~ content              = <<-EOT # forces replacement
          - # certificate serial 4f:1a:09:c2
          + # certificate serial 7d:22:e1:90
        EOT
[…]
local_file.tls_bundle: Creating...
local_file.tls_bundle: Creation complete after 0s [id=8efb1df14a5e39bb437ed03da55bf73b02904585]
local_file.tls_bundle (deposed object be61ab15): Destroying... [id=994102ed1da3549966ce7bcc54195ecf1f870ce2]
local_file.tls_bundle: Destruction complete after 0s
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

The new object was created, then the old one (now called a deposed object) was destroyed. Exactly what we asked for. Then I looked in the directory:

ls -l out/
total 0

The certificate is gone. Both the old and the new object were the same path, out/tls-bundle.pem: the new one wrote the file, then destroying the old one deleted it. The next plan wanted to create it again. This is the real-world trap with create_before_destroy: the new and old objects must be able to exist at the same time, so anything with a fixed unique name (a file path, an S3 bucket name, a security group name, a DNS record) collides or, as here, gets clobbered. On AWS the usual fix is name_prefix instead of name, so each replacement gets a fresh name. Exercise 4 applies the same fix to the certificate file.

prevent_destroy

prevent_destroy = true makes any plan that would destroy the resource fail:

terraform destroy -auto-approve -var release_version=2.15.0 -var cert_serial=7d:22:e1:90
[…]
Plan: 0 to add, 0 to change, 4 to destroy.
╷
│ Error: Instance cannot be destroyed
│ 
│   on main.tf line 25:
│   25: resource "terraform_data" "orders_db" {
│ 
│ Resource terraform_data.orders_db 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 operation stops; nothing was destroyed, including the other three resources. It also catches replacements, which is where it earns its keep: terraform plan -replace=terraform_data.orders_db failed with the same error. Put it on databases, state buckets and anything else whose loss means restoring from backup. It is not access control (anyone can delete the line), and it doesn't help if someone removes the whole resource block, because then there's no lifecycle left to check. It's a seatbelt for honest mistakes.

ignore_changes

ignore_changes tells Terraform to stop reconciling specific arguments after creation. The deploy pipeline rewrites last_deployed on every release, so I changed it in the configuration to simulate drift between the file and reality:

terraform plan
[…]
Terraform has compared your real infrastructure against your configuration
and found no differences, so no changes are needed.

Without the rule, every plan would show that field changing back. Classic real uses: an autoscaled service's desired count, which the autoscaler owns; tags that a compliance scanner adds; an AMI you only want to update deliberately. Each ignored argument is a piece of reality Terraform no longer manages, so list specific arguments, and be very suspicious of ignore_changes = all.

replace_triggered_by

replace_triggered_by replaces a resource when another resource changes, even though none of its own arguments did. Here the API token rotates on every release:

terraform plan -var release_version=2.15.0
[…]
  # random_password.api_token will be replaced due to changes in replace_triggered_by
-/+ resource "random_password" "api_token" {
      ~ bcrypt_hash = (sensitive value)
      ~ id          = "none" -> (known after apply)
      ~ result      = (sensitive value)
        # (10 unchanged attributes hidden)
    }
 
  # terraform_data.release will be updated in-place
  ~ resource "terraform_data" "release" {
        id     = "270d794c-d114-1b94-383e-2fe310d21e02"
      ~ input  = "2.14.1" -> "2.15.0"
      ~ output = "2.14.1" -> (known after apply)
    }
 
Plan: 1 to add, 1 to change, 1 to destroy.

The plan says why the token is being replaced. replace_triggered_by takes resource references (or attributes of them), not plain variables: when I tried replace_triggered_by = [var.release_version], validate refused with Only resources, count.index, and each.key may be used in replace_triggered_by. That's why the version lives in a terraform_data resource. That's the standard trick for "replace X when this value changes".

Preconditions and postconditions

Validation blocks on variables (from Variables, Locals, Outputs, and Expressions) check inputs. Conditions on resources and data sources check assumptions about everything else:

  • A precondition is checked before Terraform plans the resource. Use it for "this must be true for this resource to make sense".
  • A postcondition is checked after the resource or data source is read or planned, and can refer to the object itself as self. Use it for "whatever came back must look like this".

The deploy project has one of each. To test the postcondition, I renamed the manifest on the server so the request returned 404:

[…]
data.http.release: Read complete after 0s [id=http://127.0.0.1:8731/releases/checkout/latest.json]
 
Planning failed. Terraform encountered an error while generating this plan.
 
╷
│ Error: Resource postcondition failed
│ 
│   on main.tf line 37, in data "http" "release":
│   37:       condition     = self.status_code == 200
│     ├────────────────
│     │ self.status_code is 404
│ 
│ Release manifest request returned HTTP 404.
╵

Without that check, jsondecode would have choked on an HTML error page, or worse, a 200 response with an empty body would have produced a broken deploy.env. To test the precondition, I published a manifest with version 2.15.0-rc1:

[…]
╷
│ Error: Resource precondition failed
│ 
│   on main.tf line 65, in resource "local_file" "deploy_env":
│   65:       condition     = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+$", local.release.version))
│     ├────────────────
│     │ local.release.version is "2.15.0-rc1"
│ 
│ Release version "2.15.0-rc1" is not of the form MAJOR.MINOR.PATCH.
╵

The release candidate never reached the environment, and the error says exactly why. Conditions run on every plan, so they guard against today's data, not just the day the code was written.

Forcing a replacement with -replace

Sometimes you want a fresh object without changing the configuration: a corrupted server, a leaked token, a smoke test you want to re-run. -replace plans exactly that for one address:

terraform plan -var release_version=2.15.0 -var cert_serial=7d:22:e1:90 -replace=random_password.api_token
[…]
  # random_password.api_token will be replaced, as requested
-/+ resource "random_password" "api_token" {
      ~ bcrypt_hash = (sensitive value)
      ~ id          = "none" -> (known after apply)
      ~ result      = (sensitive value)
        # (10 unchanged attributes hidden)
    }
[…]

(The same plan also re-created the missing certificate file from the create_before_destroy section.) -replace is the successor to the older terraform taint command: the replacement shows up in the plan for review instead of being recorded in state ahead of time. Pass the flag once per resource; dependents react as usual, and prevent_destroy still applies.

Where you'll use this

The deploy project is a realistic CI deploy step: read the release CI just published, refuse anything that isn't a proper release, write the configuration the servers consume, and run a smoke test. In a pipeline it looks like this:

  • Release gating. Postconditions on the manifest (status code, checksum format) and a precondition on the version stop broken or pre-release artifacts at plan time, with an error message the on-call engineer can act on.
  • Cross-team boundaries. The network team publishes subnet IDs; application configurations read them with terraform_remote_state or a parameter-store data source, so nobody copies IDs into tfvars files by hand.
  • Zero-downtime rotations. Certificates, launch templates and load balancer target groups get create_before_destroy plus name_prefix, so traffic always has somewhere to go.
  • Guardrails on stateful resources. prevent_destroy on databases, state buckets and KMS keys; ignore_changes on fields owned by autoscalers or other tools.
  • Secret rotation tied to releases. replace_triggered_by re-creates credentials whenever a tracked resource changes.

Common mistakes

"Cycle" errors

Dependencies must form a graph without loops. I added depends_on = [terraform_data.smoke_test] to local_file.deploy_env, while smoke_test already depends on deploy_env:

╷
│ Error: Cycle:
│   local_file.deploy_env
│   terraform_data.smoke_test
│ 
│ 
╵

Terraform lists the resources in the loop. Cycles usually come from a depends_on added to "fix" an ordering problem, or from two resources referencing each other's attributes (a classic is two security groups that allow each other inline). Remove the depends_on, or break mutual references by moving the rules into separate resources.

Expecting data sources to be static

A data source is re-read on every plan. If the thing it reads changes (a newer AMI, a new manifest, an edited file), the plan changes, even though nobody touched the configuration. That's usually the point, but it surprises people when a plan for an unrelated change suddenly wants to replace a server. Read the Reading... lines and the reasons in the plan, and pin values (an AMI ID, a manifest version) when you need them to stay put.

create_before_destroy with fixed names

Covered in detail above because it's subtle: if the old and new objects share a unique name, the replacement either fails with an "already exists" error or, as with the certificate file, the destroy step removes what the create step just made. Use generated names (name_prefix, a suffix derived from the content) for anything with create_before_destroy.

Removing a prevent_destroy resource the wrong way

When you genuinely need to delete a protected resource, don't reach for -target tricks or edit state. Remove prevent_destroy in one reviewed change, then delete the resource in the next, reading the destroy plan carefully. The two-step process is the point: the decision is visible in version control.

Summary

  • data blocks read objects Terraform doesn't manage, addressed data.TYPE.NAME. They're read on every plan, so plans show real values, and they never create or destroy anything.
  • terraform_remote_state reads another configuration's outputs, at the cost of needing read access to its entire state.
  • Cloud data sources (aws_ami, aws_caller_identity) call the provider's API during plan and need real credentials even when resources can be planned with mocks.
  • References create dependencies; depends_on is only for dependencies Terraform can't see, with a comment explaining why. An unnecessary depends_on on a data source defers its read to apply time and can force needless replacements.
  • terraform graph prints the dependency graph; arrows point at what a node depends on.
  • lifecycle: create_before_destroy (needs non-colliding names), prevent_destroy (blocks destroy and replace), ignore_changes (stop managing specific arguments), replace_triggered_by (replace when another resource changes).
  • Preconditions check assumptions before a resource is planned; postconditions check results using self. -replace=ADDRESS forces a reviewed replacement of one resource.

Exercises

Exercise 1: Count the office rangeseasy

In the deploy project, add an output office_cidr_count with the number of CIDR ranges read from office-cidrs.txt. Apply it, then append 192.0.2.64/26 to the file and plan. What changes, and why didn't you have to touch any .tf file?

Show Solution
output "office_cidr_count" {
  value = length(local.office_cidrs)
}
terraform apply -auto-approve
echo '192.0.2.64/26' >> office-cidrs.txt
terraform plan | grep -E '^  # |allow |^Plan|office_cidr_count'
[…]
Outputs:
 
office_cidr_count = 2
release_version = "2.14.1"
  # local_file.nginx_allow must be replaced
            allow 203.0.113.0/24;
            allow 198.51.100.17/32;
          + allow 192.0.2.64/26;
Plan: 1 to add, 0 to change, 1 to destroy.
  ~ office_cidr_count = 2 -> 3

The data source re-read the file during plan, so the new range flowed into nginx_allow and the output. The security team can change the allowlist with a one-line pull request to a text file.

Exercise 2: Reject a manifest without a checksummedium

Add a second postcondition to data.http.release that fails unless the manifest's sha256 field is exactly 64 lowercase hex characters. Test it by publishing a manifest with "sha256": "TODO".

Hint

self.response_body is the raw JSON text. Decode it inside the condition and wrap the regex() in can().

Show Solution

Add this inside the existing lifecycle block, after the status-code check:

    postcondition {
      condition     = can(regex("^[0-9a-f]{64}$", jsondecode(self.response_body).sha256))
      error_message = "Release manifest has no valid sha256 checksum."
    }

With the good manifest the plan reported No changes. With "sha256": "TODO":

[…]
Planning failed. Terraform encountered an error while generating this plan.
 
╷
│ Error: Resource postcondition failed
│ 
│   on main.tf line 42, in data "http" "release":
│   42:       condition     = can(regex("^[0-9a-f]{64}$", jsondecode(self.response_body).sha256))
│     ├────────────────
│     │ self.response_body is "{\n  \"version\": \"2.14.1\",\n  \"artifact\": \"checkout-2.14.1.tar.gz\",\n  \"sha256\": \"TODO\",\n  \"published\": \"2026-11-09T18:20:00Z\"\n}\n"
│ 
│ Release manifest has no valid sha256 checksum.
╵

A data source can have several postconditions, and each reports separately. Checking the checksum's format doesn't prove the artifact is intact; the servers still have to verify the download against it.

Exercise 3: Re-run the smoke test on demandmedium

The smoke test only runs when the release version changes. Re-run it now, without editing any file, and confirm from the output that the provisioner executed again.

Show Solution
terraform apply -auto-approve -replace=terraform_data.smoke_test
[…]
  # terraform_data.smoke_test will be replaced, as requested
-/+ resource "terraform_data" "smoke_test" {
[…]
Plan: 1 to add, 0 to change, 1 to destroy.
terraform_data.smoke_test: Destroying... [id=b58d9b86-efa1-2d8c-9c77-62c4d659a1e8]
terraform_data.smoke_test: Destruction complete after 0s
terraform_data.smoke_test: Creating...
terraform_data.smoke_test: Provisioning with 'local-exec'...
terraform_data.smoke_test (local-exec): Executing: ["/bin/sh" "-c" "grep -q '^APP_VERSION=' out/deploy.env && echo 'deploy.env looks valid'"]
terraform_data.smoke_test (local-exec): deploy.env looks valid
terraform_data.smoke_test: Creation complete after 0s [id=91ff9bbb-1d67-722c-0779-21aa4b272aeb]
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

Provisioners run only when their resource is created, so replacing the resource is how you re-run one. Nothing else in the project changed.

Exercise 4: Make the certificate rotation safehard

Fix the create_before_destroy trap in the lifecycle project so that rotating cert_serial leaves a certificate file in out/ at every point. Prove it by rotating twice and listing the directory after each apply.

Hint

The old and new objects need different paths. Derive part of the filename from the serial; replace() can strip the colons.

Show Solution
resource "local_file" "tls_bundle" {
  filename        = "${path.module}/out/tls-bundle-${replace(var.cert_serial, ":", "")}.pem"
  file_permission = "0644"
  content         = "# certificate serial ${var.cert_serial}\n"
 
  lifecycle {
    create_before_destroy = true
  }
}
terraform apply -auto-approve -var release_version=2.15.0 -var cert_serial=7d:22:e1:90
ls out
terraform apply -auto-approve -var release_version=2.15.0 -var cert_serial=91:0b:5e:3a
ls out
[…]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
tls-bundle-7d22e190.pem
[…]
+/- resource "local_file" "tls_bundle" {
local_file.tls_bundle: Creating...
local_file.tls_bundle: Creation complete after 0s [id=d27acb706a26bbcb582a4db255766c2a44bdfd12]
local_file.tls_bundle (deposed object e079d278): Destroying... [id=8efb1df14a5e39bb437ed03da55bf73b02904585]
local_file.tls_bundle: Destruction complete after 0s
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
tls-bundle-910b5e3a.pem

The first apply just recreated the file the trap had deleted, now under its new name. On the second rotation the new file existed before the old one was removed, and the old one's deletion couldn't touch it. Whatever reads the certificate would point at the current filename, for example through a symlink or a config value taken from local_file.tls_bundle.filename, which is the same design as name_prefix on AWS.


Tested with: Terraform v1.17.1 on Ubuntu 24.04 (WSL2, linux_amd64), November 2026, with hashicorp/local v2.9.1, hashicorp/random v3.9.1, hashicorp/http v3.6.3 and hashicorp/aws v6.72.0. All local examples were applied and every output is from a real run, trimmed where marked […]. The artifact server was python3 -m http.server on 127.0.0.1 serving a real tarball and manifest. The AWS data source configuration passed terraform validate; terraform plan was run only with fake credentials and failed with the authentication errors shown, so no AMI lookup or caller identity was actually returned and nothing was created in AWS. Graphviz isn't installed in my lab, so the dot -Tsvg rendering command was not run.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Terraform tutorial here is tested end to end before publishing.