Q: How do you make Terraform wait for one resource before creating another?
To make Terraform wait for one resource before creating another, create a dependency edge: reference an attribute of the first resource (implicit dependency) or use depends_on when the relationship is not visible in arguments.
Want to master this scenario in a live sandbox? KodeKloud's HashiCorp Certified Terraform Associate (003) Interactive Labs covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: To <strong>make Terraform wait for one resource</strong> before creating another, create a dependency edge: reference an attribute of the first resource (implicit dependency) or use <code>depends_on</code> when the relationship is not visible in arguments. When the provider reports a resource complete before it is truly usable, as happens with IAM or DNS propagation, add a deliberate delay with <code>time_sleep</code> or a proper retry mechanism. Interviewers ask this to see whether you understand Terraform dependency graph, parallelism and eventual consistency rather than reaching for sleeps. The senior answer is to prefer references, use depends_on sparingly and treat time-based waits as a last resort.
Mental model: Terraform builds a dependency graph
Terraform runs independent resources in parallel and orders only the ones with a known dependency.
- Implicit dependency: using
aws_iam_role.app.arninside another resource tells Terraform to create the role first. This is the preferred form. - Explicit dependency:
depends_on = [aws_iam_role_policy_attachment.app]orders resources that share no attribute reference. - Parallelism: by default up to 10 operations run concurrently (
-parallelism), so missing edges show up as race conditions. - Destroy order: dependencies reverse on destroy automatically, which is another reason to model them honestly.
- Modules: outputs carry dependency information, so referencing
module.network.subnet_idsalready waits for the module resources behind that output.
Hands-on: make Terraform wait for one resource
Combine a reference, depends_on and a time_sleep where propagation delay is real.
resource "aws_iam_role" "app" {
name = "app-role"
assume_role_policy = data.aws_iam_policy_document.trust.json
}
resource "aws_iam_role_policy_attachment" "app" {
role = aws_iam_role.app.name
policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
}
# Give IAM time to propagate
resource "time_sleep" "iam_propagation" {
depends_on = [aws_iam_role_policy_attachment.app]
create_duration = "30s"
}
resource "aws_lambda_function" "app" {
function_name = "my-app"
role = aws_iam_role.app.arn
runtime = "python3.12"
handler = "main.handler"
filename = "build/app.zip"
depends_on = [time_sleep.iam_propagation]
}
- IAM case: a role policy attachment can succeed before IAM is globally consistent, so the next service call may briefly fail with an access error.
- time_sleep: from the
hashicorp/timeprovider, it waits a setcreate_durationafter its own dependencies complete. - Chain it: make the sleep depend on the policy attachment and make the consumer depend on the sleep.
- Keep it short: choose the smallest delay that works and document why it exists.
- Verify the delay is needed: remove the sleep in a scratch environment and apply; if it succeeds repeatedly, the wait was unnecessary.
Better options than a fixed sleep
A sleep is a guess. Use real readiness signals when the provider or tooling offers them.
resource "terraform_data" "wait_for_api" {
depends_on = [aws_lb.api]
provisioner "local-exec" {
command = "for i in $(seq 1 30); do curl -sf https://${aws_lb.api.dns_name}/health && exit 0; sleep 10; done; exit 1"
}
}
- Resource timeouts: many resources support a
timeoutsblock, and providers often poll until the resource reaches the desired state; extend it for slow services. - Wait resources: some providers have dedicated waiters, for example certificate validation resources that wait for DNS validation to complete.
- Provisioner as last resort: a
local-execthat polls an endpoint can gate completion, but provisioners are discouraged and only run at creation. - Use terraform_data:
terraform_data(Terraform 1.4 and later) withtriggers_replaceand a polling provisioner replaces oldernull_resourcepatterns. - Retries: some providers expose retry settings; for example the AWS provider supports
max_retriesfor throttled API calls, which is different from waiting for readiness.
Failure modes and verification
Wrong ordering shows up as flaky applies, so verify with graphs and repeat runs.
- Inspect order:
terraform graph | dot -Tsvg > graph.svgvisualises edges; a missing line between two resources explains a race. - Overusing depends_on: on modules or data sources it can force the data read to apply time and widen unknowns in plans. Prefer attribute references.
- Time only at creation: time_sleep waits when created; it does not re-wait on later updates unless
triggerschange. - Verify idempotence: test in a clean account: apply once from scratch and expect success without a retry, then plan expecting no changes.
- Failure signature: typical symptoms are access denied or not found errors that vanish on a rerun, which indicate eventual consistency rather than a real misconfiguration.
Design guidance: when waiting is a smell
Needing waits often points to a modelling problem that is better solved structurally.
- Split stacks: if one layer must be fully ready before another starts, put them in separate root modules and apply them in order in CI.
- Readiness belongs to the platform: for Kubernetes, rely on readiness probes and health checks rather than Terraform sleeps.
- Document delays: add a comment naming the API behaviour that forces each wait, so a later engineer can remove it when the provider fixes it.
- Observe in CI: track apply duration; sudden growth often reveals piled-up sleeps or very long timeouts.
- I make Terraform wait by creating a dependency: reference the other resource attribute, or use depends_on when no attribute links them.
- I verify with terraform graph and by applying from scratch in a clean account to prove it works without a retry.
- I automate readiness with provider timeouts and waiters, and use time_sleep or a polling terraform_data only for documented propagation delays.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Adding time_sleep before trying references A sleep hides a missing dependency, wastes time on every run and still fails when propagation is slower than the guess.
- Putting depends_on on whole modules by habit It makes every resource in the module depend on the target and can defer data reads to apply, producing noisy plans.
- Using -target to enforce ordering It skips parts of the graph and can leave state inconsistent; model the dependency in code instead.
- Expecting provisioners to rerun on every apply They run only when the resource is created or destroyed, so a later readiness check needs a trigger or a different design.