⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Terraform & IaC Interview Questions Scenario 50 of 120 in Terraform & IaC
Staff SRE / Principal Architect [L3] Terraform Terraform Modules & State Staff SRE Scenario [L3]
🎯 Target Role / Context: Terraform Scenario #45 (L3) · Use VPC ID from another module

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:

#Terraform #L3 #IaC #Cloud Infrastructure #IAM
🎙️ Candidate Opening & Architectural Context
"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."
Advertisement
⚡ Recommended Practice Lab

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.

1️⃣

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.arn in 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.
2️⃣

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/time supplies time_sleep with create_duration and destroy_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 triggers to 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/time provider version on the registry and pin a constraint; the time_sleep resource has been stable for years.
Advertisement
3️⃣

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 -Tsvg shows 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.
4️⃣

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.
5️⃣

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_on or 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.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Use references first, <code>depends_on</code> second, and a scoped <code>time_sleep</code> only for proven eventual-consistency races such as IAM propagation."
⚡ 60-Second Elevator Pitch Talking Points
  • 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.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Relying on file order Terraform ignores it; independent resources run in parallel.
  2. Adding a sleep without a depends_on edge to it The consumer may start before the sleep, so the wait does nothing.
  3. Using local-exec sleep as the default tool It is invisible to the graph, platform dependent and brittle.
  4. Setting one large global delay It slows every apply and still does not guarantee readiness.
Advertisement
Want more Terraform & IaC scenarios?
Explore our complete collection of scenario-based Terraform & IaC interview runbooks.
Browse All Terraform & IaC Questions →