What Is depends_on in Terraform? Implicit vs Explicit Dependencies and the lifecycle Block

I added depends_on and nginx still started before its init finished. Implicit vs explicit dependencies and every lifecycle rule, tried on local Docker.

By Mirac Can Yılmaz 14 min read
What Is depends_on in Terraform? Implicit vs Explicit Dependencies and the lifecycle Block - DevOps yazısının kapak görseli

I added depends_on to a Docker container that Terraform manages, and it still started before the init container it depended on had finished. That init container, the one that writes nginx's config, was still running. nginx came up, read an empty directory, and served the image's default page. depends_on had done exactly what it does: it waited for the init container to be created, and for a one-shot container "created" means "started", not "finished". Here I look at what Terraform orders, what it leaves to the provider, and what the lifecycle block adds on top. Everything runs on a laptop with Docker, no cloud account. Terragrunt, which takes the same idea between state files, is the next post.

What is depends_on in Terraform?

Terraform builds a graph of every resource in your configuration and walks it in dependency order, in parallel where nothing connects two nodes. The edges of that graph come from two places:

  • Implicit dependencies: any expression that references another resource. image = docker_image.app.image_id is an edge from the container to the image. Most dependencies should be this kind, because they also carry the value.
  • Explicit dependencies: the depends_on meta-argument, a list of resource addresses. You use it when there is a real ordering requirement but no attribute to reference, for example a container that must start after another container has finished seeding a volume.

Both do the same thing: Terraform creates the dependency first and destroys it last. What neither does is wait for the dependency to be ready in any sense beyond what the provider reports as "created". That gap is where most surprises live.

The lifecycle block is a separate set of rules about how a single resource is replaced and protected: create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by, and the precondition and postcondition checks.

The problem, and why it matters

Infrastructure code that works on the second run is a trap. If a resource starts before the thing it needs exists, the first apply fails, the second one passes because the first half-finished, and the team learns to "just run it again". Nobody writes down why. The day the pipeline runs from a clean state, in a new account or a new region, the failure comes back and the person on call has never seen it.

The second half of the problem is what happens when a resource has to be replaced. The default order is destroy, then create. For a database or a load balancer that is a real outage, and it is invisible in plan output: the plan says "1 to add, 1 to destroy" either way. The order and the overlap are decided by one line in a lifecycle block, or by its absence.

Both problems get worse as the code grows. The usual fix for a large configuration is to split it, and the moment you split state you have dependencies Terraform itself can no longer see; that part is the next post.

What dependencies and lifecycle rules give you

In practice What changed in the lab
Implicit dependency (a reference) the value and the ordering travel together the container that used docker_image.app.image_id waited for the build; the one that used the tag as a string did not
depends_on ordering where no attribute exists to reference nginx waited for the init container to be created; it took one more provider setting to make it wait for it to finish
create_before_destroy the new instance exists before the old one goes a version change stopped taking the site down; it also meant two versions answered at once for a moment
prevent_destroy a plan that would delete the resource is refused terraform destroy stopped before touching anything, with the volume named in the error
ignore_changes drift on chosen attributes is not reverted a docker update made at runtime stopped showing up as a change to undo

How it works: the graph

Diagram: how Terraform decides order. On the left, a reference inside an expression draws an edge from the container to the image, so the image is created first and destroyed last. In the middle, the same two resources with the image tag written as a string have no edge; Terraform starts both at once and the container loses the race. On the right, depends_on draws the edge by hand, but the edge ends at "created", and for a one-shot container the provider reports created the moment the process starts.

terraform graph -type=plan prints the graph Terraform is about to walk. In the base lab there is a single network and a Traefik container whose command line interpolates ${docker_network.lab.name}. That one interpolation is the whole dependency: the output has an edge docker_container.traefik -> docker_network.lab, so the network is created first and, on destroy, removed last. No depends_on anywhere.

Everything else in this post is what happens when that edge is missing, when it is drawn by hand, and what the lifecycle block does once the edge is there.

The lab

Five small Terraform directories against one Docker daemon. The web containers sit behind a Traefik that discovers them through labels, so a container can be replaced and I can watch the site from the outside while it happens.

1. A string is not a reference

The image is built by Terraform. The container names it as a string:

resource "docker_image" "app" {
  name = "tf-lab-app:local"
  build {
    context = "${path.module}/app"
  }
}

resource "docker_container" "app" {
  name  = "tf-lab-app"
  image = "tf-lab-app:local"   # same tag the build produces, but only a string
}

Terraform sees two unrelated resources and starts both. The build takes a while; the container create does not, so it asks Docker for an image that does not exist yet and Docker tries to pull it from a registry:

Terminal: the first apply with the image tag as a string. docker_image.app and docker_container.app start together, the image finishes building a moment later, and the container fails with "Unable to create container with image tf-lab-app:local: unable to pull image ... pull access denied". A second apply of the same code passes, because the image now exists locally.

Run the same code again and it passes, because the first run left the image behind. That is the "works the second time" pattern from the problem section, reproduced on purpose. The same missing edge shows up on destroy: image and container are removed in parallel, and the image removal fails because a container is still using it.

The fix is the reference, image = docker_image.app.image_id. The graph gains its edge, the build finishes before the container is created, and the destroy runs in reverse. Nothing else changes.

2. depends_on orders creation, not completion

An init container sleeps for a moment, then writes nginx's server block into a volume. The web container mounts that volume as /etc/nginx/conf.d. nginx reads that directory once, at startup. Nothing in the web container references the init container, so there is no edge to draw from a value; this is exactly what depends_on is for.

resource "docker_container" "web" {
  name  = "tf-lab-web02"
  image = docker_image.nginx.image_id

  depends_on = [docker_container.init]

  volumes {
    volume_name    = docker_volume.conf.name
    container_path = "/etc/nginx/conf.d"
  }
}

Three runs, three variants of the same two containers:

Terminal: three applies of the init-and-web pair. Without ordering, web is created while init is still sleeping and curl returns nginx's default welcome page. With depends_on on web, init reports "Creation complete after 0s", web starts immediately and curl still returns the welcome page. With depends_on and attach = true on the init container, init reports creation complete only after its process exits, web starts after it, and curl returns "seeded by init".

  • No ordering. Both start together. nginx wins, finds an empty volume, Docker seeds it from the image, and nginx keeps the default config for as long as it lives. A moment later the init container has written the real config into the volume; nginx never looks again.
  • depends_on on web. The order is right and the result is the same. Terraform waited for init to be created, and the Docker provider reports a container created the moment it is started. Init was still sleeping when web came up.
  • depends_on plus attach = true on init. Now the provider does not return from "create" until the process exits. Init's creation takes as long as its script; web starts after; nginx reads the seeded config.

The lesson is not "use attach". It is that depends_on hands you off to the provider's definition of done, and you have to know what that is for the resource you are waiting on. For a one-shot job it is usually "started" unless you say otherwise; for a managed database in a cloud it is usually "available"; for a Kubernetes Deployment it depends on whether wait_for_rollout is set. The dependency is only as strong as that definition.

3. create_before_destroy, and what it costs

Changing the image tag forces a new container. With no lifecycle block the order is destroy, then create, and the site is simply gone in between: first connection errors while the old container is removed, then Traefik's 404 while the new one is created and waits to become healthy. Long enough to notice from the outside.

resource "docker_container" "web" {
  name  = "tf-lab-web-${substr(sha1(var.image), 0, 8)}"
  image = docker_image.web.image_id

  healthcheck {
    test     = ["CMD", "wget", "-qO-", "http://127.0.0.1/"]
    interval = "1s"
  }
  wait = true   # creation ends when the healthcheck passes

  lifecycle {
    create_before_destroy = true
  }
}

Terminal: the same image change three ways. With the default order Terraform destroys the old container, creates the new one, and the request log in between shows connection errors and then 404s until the new one is healthy. With create_before_destroy and a fixed container name, the apply fails with "Conflict. The container name /tf-lab-web is already in use" and the old container keeps running. With create_before_destroy and a name derived from the image, the new container is created and reported healthy first, the old one is destroyed as a "deposed object", and the request log shows both nginx versions answering in turn for about a second, then only the new one.

Two things had to change for create_before_destroy to work, and both are worth knowing before you flip it on in production:

  • The new instance must not collide with the old one. With a fixed name, Docker refuses to create the second container while the first exists. The apply fails, and because the destroy only happens after a successful create, the old container stays up. Safe, but not what you wanted. The fix here is a name derived from the image; in a cloud it is usually a name_prefix, a random suffix, or letting the provider name the thing.
  • For a moment, two versions exist. Traefik saw both containers behind the same router and sent requests to each in turn until the old one was gone. If the two versions write to the same database with different schemas, that moment is where you find out. Terraform calls the outgoing instance a deposed object, and you will see that word in the apply output.

With both in place the switch is close to uninterrupted. What is left is the proxy noticing that a backend left, which is not Terraform's problem to solve.

4. prevent_destroy and ignore_changes

prevent_destroy on the data volume does one thing: any plan that would delete it is refused before anything is touched. There is no CLI flag to override it. To actually delete the volume you remove the line, apply, and then destroy, which is the point. It stops the Friday afternoon terraform destroy in the wrong directory.

ignore_changes is for attributes that someone or something else owns at runtime. I changed the container's restart policy and memory limit with docker update, the way an operations team would during an incident. The next plan wanted to put them back:

Terminal: after a docker update on the running container, terraform plan shows memory 256 -> 128 and restart "always" -> "no" as changes to make, with exit code 2. With ignore_changes = [restart, memory, memory_swap] in the lifecycle block the plan has no changes and exits 0. Below, terraform destroy on the configuration with prevent_destroy set on the volume fails with "Instance cannot be destroyed" and names the resource.

With the two attributes in ignore_changes the plan is clean. The cost is that your code no longer describes those values; the first attribute you ignore is also the first one nobody can find in Git six months later. Keep the list short and comment why each entry is there.

5. The rest of lifecycle: replace_triggered_by and conditions

replace_triggered_by replaces a resource when another resource changes, even if none of its own attributes did. It takes resource addresses, not variables, so the documented pattern is to wrap the value in a terraform_data:

resource "terraform_data" "release" {
  input = var.release
}

resource "docker_container" "web" {
  # ... the container never reads var.release ...

  lifecycle {
    replace_triggered_by = [terraform_data.release]

    precondition {
      condition     = var.port > 1024
      error_message = "Ports below 1024 need root on the host."
    }
  }
}

Bumping release from r1 to r2 produced a plan with docker_container.web will be replaced due to changes in replace_triggered_by and a new container ID, with nothing in the container's own configuration changed. This is how you force a rotation on purpose: a new release label, a rotated secret, a changed base image that the resource does not reference directly.

precondition and postcondition are checks with error messages. The precondition on the port refused -var port=80 at plan time, before any API call. A postcondition runs after the resource exists and fails the apply if the result does not match what you promised; I used one to assert the container came up with a network address.

Where it broke

1. pull access denied for tf-lab-app: the image was a string, not a reference

The container's image was the tag the build produces, written as a literal. Terraform had no edge between them, started both, and the container asked Docker for an image that was still being built. The second apply passed. The fix is docker_image.app.image_id; the symptom to remember is "fails from clean, passes on retry".

2. depends_on did not wait for the init container to finish

It waited for it to be created, and the Docker provider considers a container created when it is started. The init script was still sleeping when nginx read its config directory. attach = true on the init container makes creation last until the process exits, and then depends_on means what I meant.

3. The container name "/tf-lab-web" is already in use: create_before_destroy with a fixed name

Terraform tried to create the replacement while the original still existed, Docker refused the duplicate name, and the apply failed. The old container kept running. Any create_before_destroy resource needs a name or identifier that can exist twice.

4. Instance cannot be destroyed: prevent_destroy did its job on cleanup day

The lab's own cleanup hit it. Removing the flag in code and applying first is the only way through, and that is the feature, not a bug. Put the flag only on things you would be sorry to lose.

5. unable to remove repository reference ... container is using its referenced image

Same missing edge as the first failure, seen from the destroy side: with no dependency, the image removal and the container removal ran at the same time and the image lost. One reference fixes both directions.

The trade-off, side by side

Destroy first (default) create_before_destroy
Plus one instance at a time, no name or capacity collisions, simplest to reason about the service stays up through a replacement; a failed create leaves the old instance running
Minus the resource is gone between destroy and create, and the plan output does not show it needs non-colliding names, double capacity for a moment, and two versions live at once
Fits stateless things nobody is waiting on, dev environments, anything with a fixed identity anything with traffic on it, as long as the application tolerates an overlap
Implicit dependency (a reference) depends_on
Plus ordering and value in one place; removing the reference removes the edge works when there is no attribute to reference; the intent is visible
Minus easy to lose by writing a value as a string waits only for "created" as the provider defines it; easy to over-use and slow plans down
Fits the default for almost everything one-shot jobs, side effects, resources that only exist to prepare another

None of these columns is the right one. I leave create_before_destroy off by default and turn it on per resource once I know the name can exist twice and the app can take an overlap. I reach for depends_on only when I have tried and failed to find an attribute to reference.

When to use which

  • Reference the attribute whenever one exists. A string that happens to match is not a dependency.
  • depends_on for side effects and one-shot jobs, and check what "created" means for that resource type. For containers, attach or wait; for cloud resources, read the provider's notes on when create returns.
  • create_before_destroy on anything with traffic, after making sure the name can exist twice and the app tolerates two versions.
  • prevent_destroy on stateful things you cannot recreate: volumes, databases, buckets. Nowhere else, or you will stop reading the error.
  • ignore_changes only for attributes something else owns at runtime, with a comment per entry.
  • replace_triggered_by through a terraform_data when the trigger is a value, not a resource.

Your call

I keep create_before_destroy off by default and switch it on resource by resource, and I put prevent_destroy only on volumes and databases. That is right for my setups this month; it is not a rule for yours. Two things I would like to hear from real repos, because a laptop lab cannot answer them:

  • Is create_before_destroy your default, or an exception you add when something hurts?
  • Has prevent_destroy ever stopped a real mistake for you, or has it only ever been in the way?

I am not after who is right. I want the pluses and minuses in the tables above to be visible to everyone who reads this, in words from real infrastructure, and the comments are where that happens. If you would rather vote than write, the same question is a poll on my LinkedIn post for this article: https://www.linkedin.com/in/mirac-can-yilmaz

Summary

  • Terraform orders resources by the edges in its graph. A reference draws an edge; a matching string does not. "Fails from clean, passes on retry" is the symptom of a missing edge.
  • depends_on draws the edge by hand, but it waits for "created" as the provider defines it. For a one-shot container that is "started" unless you set attach or wait.
  • create_before_destroy keeps the service up through a replacement, at the price of a non-colliding name and two versions alive at once. The default order takes the resource down and the plan does not say so.
  • prevent_destroy, ignore_changes, replace_triggered_by and the condition blocks are guards around one resource; each is a promise your code stops describing, so keep them few and commented.

Next in the series

This is post 7 of Core Skills. The previous one, What Is Observability? Prometheus and Grafana on kind, looked at how a cluster tells you a pod stopped and who hears it first; this one looked at how Terraform decides what comes first, and what it quietly leaves to the provider. Next: the same dependency one level up, between state files, with Terragrunt and a second provider in the same repo.

The code for this lab (the five Terraform directories, the Traefik front and the request logger) is shared with Lab Access members on Buy Me a Coffee; the repo invite comes by email after you join: https://buymeacoffee.com/miraccanyilmaz/membership

About the author

Mirac Can Yılmaz

Mirac Can Yılmaz DevOps & Platform Engineer

I work as a DevOps and platform engineer with Kubernetes, GitOps (Argo CD), CI/CD and Terraform. Every post here was tried and measured in my own lab, on kind and Talos clusters: the commands, the errors and the numbers as they happened. The lab code is shared with Lab Access members on Buy Me a Coffee.

İnsanın en büyük hatalarından biri de doğru zamanı yanlış kişilerle doldurmaktır.
Charles Bukowski