Q: How do you handle a situation where Terraform needs to create resources in a specific order (e.g., wait 30 seconds for IAM propagation)?
Use time_sleep resource from the hashicorp/time provider:
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 make Terraform create resources in a specific order, express the order as dependencies: reference attributes so Terraform infers edges, add <code>depends_on</code> where no attribute links two resources, and use the <code>time_sleep</code> resource from the HashiCorp time provider when you must wait for eventual consistency, such as IAM propagation. Terraform does not run top to bottom; it walks a dependency graph in parallel. Interviewers want to hear that you reach for references first, use a delay only as a targeted last resort, and avoid <code>local-exec</code> sleeps.
How ordering works in Terraform
The file order is irrelevant; the dependency graph decides. Once you accept that ordering is a graph property, every fix becomes a question of adding the right edge.
- Implicit dependency: using
aws_iam_role.app.arnin another resource makes Terraform create the role first. This is the preferred mechanism. - Explicit dependency:
depends_on = [ ... ]adds an edge when the relationship is real but invisible in arguments, for example an IAM policy that a Lambda needs at runtime. - Parallel by default: independent resources are created concurrently (default
-parallelism=10), which exposes race conditions with eventually consistent APIs. - Destroy order: reversed automatically; dependents are destroyed before the things they depend on.
- Why races happen: IAM is eventually consistent, so a role or policy can be accepted by the API but not yet visible to another service that tries to use it moments later.
Hands-on: create resources in a specific order with time_sleep
Insert a controlled wait between the IAM change and its first consumer.
terraform {
required_providers {
time = {
source = "hashicorp/time"
version = "~> 0.11"
}
}
}
resource "aws_iam_role_policy_attachment" "exec" {
role = aws_iam_role.fn.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
resource "time_sleep" "wait_30_seconds" {
depends_on = [aws_iam_role_policy_attachment.exec]
create_duration = "30s"
}
resource "aws_lambda_function" "fn" {
function_name = "my-fn"
role = aws_iam_role.fn.arn
# ...
depends_on = [time_sleep.wait_30_seconds]
}
- Provider:
hashicorp/timesuppliestime_sleepwithcreate_durationanddestroy_duration. - Wiring: the sleep depends on the IAM resource, and the consumer depends on the sleep. Both edges are needed.
- Triggers: by default the sleep runs once; use
triggersto wait again when the upstream value changes. - Scope it: keep the delay small and attached to one pair of resources, not global.
- Version note: check the current
hashicorp/timeprovider version on the registry and pin a constraint; thetime_sleepresource has been stable for years.
Verify the order and the fix
Confirm both that the dependency exists and that the race is gone. Seeing the wait in the log and the edge in the graph together is good evidence that your fix is wired correctly.
terraform apply
# ...
# time_sleep.wait_30_seconds: Creating...
# time_sleep.wait_30_seconds: Still creating... [10s elapsed]
# time_sleep.wait_30_seconds: Creation complete after 30s
# aws_lambda_function.fn: Creating...
- Graph:
terraform graph | dot -Tsvgshows the edge from the consumer to the sleep and from the sleep to the IAM resource. - Apply log: the output shows
time_sleep.wait_30_seconds: Still creating...before the consumer starts. - Re-run: apply from a clean state in a test account several times; a race may only fail occasionally.
- Error signature: messages like "role cannot be assumed" or "invalid principal in policy" right after creation point to eventual consistency.
Alternatives and failure modes
A sleep is a guess; know when it is wrong. A delay hides the symptom of a race, so always understand which API is eventually consistent before adding one.
- Fixed delay may be too short: propagation time varies. Check for provider retry behavior first, and keep the delay as a safety margin rather than a proof.
- local-exec sleep:
provisioner "local-exec" { command = "sleep 30" }works but is opaque, platform dependent and not modeled in the graph. Provisioners are a last resort. - Better signals: where the API offers a waiter or a data source that confirms readiness, use it instead of time.
- Split applies: for rare cases, apply a foundational layer first in a separate state or pipeline stage.
- Provider retries: many AWS provider resources already retry on known propagation errors, so a delay is only needed when you can reproduce a failure.
Production practice
Keep ordering explicit and documented. Explicit, commented ordering is easier to maintain than clever tricks that nobody remembers later.
- Comment the why: note the failure that prompted each
depends_onor delay so future readers do not delete it. - Review delays: periodically test removing them after provider upgrades, since providers often add retries.
- Pipeline stages: separate foundation (IAM, networking) from workloads to reduce intra-apply races.
- Cost of waiting: every sleep adds to total apply time, which matters in pipelines that provision many environments; measure before and after.
- Testing in a clean account: run the full apply in a fresh sandbox periodically, since a warm account hides propagation races that appear on first creation.
- Terraform orders by dependency graph, so I use attribute references, depends_on, and time_sleep for IAM propagation.
- I verify with terraform graph and apply logs, and test from a clean account to catch races.
- I document each delay and revisit it after provider upgrades, avoiding local-exec sleeps.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Relying on file order Terraform ignores it; independent resources run in parallel.
- Adding a sleep without a depends_on edge to it The consumer may start before the sleep, so the wait does nothing.
- Using local-exec sleep as the default tool It is invisible to the graph, platform dependent and brittle.
- Setting one large global delay It slows every apply and still does not guarantee readiness.