⚡ ~/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 32 of 120 in Terraform & IaC
Senior DevOps / SRE [L2] Terraform Terraform Modules & State Production Scenario [L2]
🎯 Target Role / Context: Terraform Scenario #27 (L2) · Use VPC ID from another module

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.

#Terraform #L2 #IaC #Cloud Infrastructure #IAM
🎙️ Candidate Opening & Architectural Context
"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."
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 <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.

1️⃣

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.arn inside 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_ids already waits for the module resources behind that output.
2️⃣

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/time provider, it waits a set create_duration after 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.
Advertisement
3️⃣

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 timeouts block, 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-exec that 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) with triggers_replace and a polling provisioner replaces older null_resource patterns.
  • Retries: some providers expose retry settings; for example the AWS provider supports max_retries for throttled API calls, which is different from waiting for readiness.
4️⃣

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.svg visualises 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 triggers change.
  • 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.
Pro Tip: Do not use <code>-target</code> to force ordering; it is for exceptional recovery and leaves the graph incomplete.
5️⃣

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.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Fix ordering with a real attribute reference first, then depends_on, and only add time_sleep for proven eventual-consistency gaps, with a comment explaining which API needs the delay."
⚡ 60-Second Elevator Pitch Talking Points
  • 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.
⛔ 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. 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.
  2. 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.
  3. Using -target to enforce ordering It skips parts of the graph and can leave state inconsistent; model the dependency in code instead.
  4. 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.
Advertisement
Want more Terraform & IaC scenarios?
Explore our complete collection of scenario-based Terraform & IaC interview runbooks.
Browse All Terraform & IaC Questions →