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

Q: How do you handle conditionally creating a resource in Terraform?

Use count:

#Terraform #L2 #IaC #Cloud Infrastructure
🎙️ Candidate Opening & Architectural Context
"<strong>Conditionally creating a resource in Terraform</strong> is done by setting <code>count</code> to <code>0</code> or <code>1</code> from a boolean, or by using <code>for_each</code> over an empty or single-element map. Terraform has no <code>if</code> statement for resources, so the pattern is to vary how many instances exist. Interviewers ask because the details matter: referencing a resource that may not exist, the unknown-value limit on <code>count</code>, address changes when toggling, and optional nested blocks all trip up real modules."
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: <strong>Conditionally creating a resource in Terraform</strong> is done by setting <code>count</code> to <code>0</code> or <code>1</code> from a boolean, or by using <code>for_each</code> over an empty or single-element map. Terraform has no <code>if</code> statement for resources, so the pattern is to vary how many instances exist. Interviewers ask because the details matter: referencing a resource that may not exist, the unknown-value limit on <code>count</code>, address changes when toggling, and optional nested blocks all trip up real modules.

1️⃣

Mental model: instances, not if-statements

A resource block declares a template; count or for_each decides how many copies exist, and zero is a valid answer.

  • count toggle: count = var.enable_x ? 1 : 0 is the simplest and most common form. The resource is then addressed as aws_x.this[0].
  • for_each toggle: for_each = var.enable_x ? { main = true } : {} gives a stable string key instead of a numeric index, which survives reordering.
  • Modules: count and for_each on module blocks work since Terraform 0.13, so you can toggle an entire stack of resources at once.
  • Known at plan time: the condition must be known during plan. Base it on input variables or static locals, not on attributes of resources created in the same run.
  • Choosing between them: use count for a simple on or off switch, and for_each when you manage a collection or want a stable key that appears in the state address and in plan output.
2️⃣

Hands-on: conditionally creating a resource in Terraform with count

Show the toggle, and then the part most people miss: safely referencing the resource that might not exist.

variable "create_bucket" {
  type    = bool
  default = true
}

resource "aws_s3_bucket" "logs" {
  count  = var.create_bucket ? 1 : 0
  bucket = "my-app-logs-prod"
}

output "logs_bucket_arn" {
  value = one(aws_s3_bucket.logs[*].arn)   # null when not created
}
  • Create: a boolean variable drives count. Give the variable a default and a description so callers know the toggle exists.
  • Reference safely: use one(aws_x.this[*].id) (Terraform 0.15 and later), which returns null when there are zero instances and the value when there is one.
  • Alternative: try(aws_x.this[0].id, null) also works but can mask unrelated errors, so prefer one().
  • Output: publish the nullable value as a module output so callers can handle absence explicitly.
Advertisement
3️⃣

Optional arguments and nested blocks with dynamic

Not everything conditional is a whole resource; sometimes only a block or argument should appear.

resource "aws_lb_listener" "https" {
  count             = var.enable_https ? 1 : 0
  load_balancer_arn = aws_lb.app.arn
  port              = 443
  protocol          = "HTTPS"
  certificate_arn   = var.certificate_arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.app.arn
  }
}

resource "aws_security_group" "app" {
  name = "app"
  dynamic "ingress" {
    for_each = var.enable_https ? [443] : []
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["10.0.0.0/8"]
    }
  }
}
  • Optional argument: set it to null to omit it, for example kms_key_id = var.kms_key_arn with a null default.
  • Optional nested block: use a dynamic block iterating a list that is empty when the feature is off.
  • Nested toggles: keep dynamic blocks for small cases; heavy use makes plans hard to read, so consider two resource variants instead.
  • Validation: add a validation block so dependent variables (like a certificate ARN when HTTPS is on) cannot be left unset.
4️⃣

Failure modes: unknown counts and shifting addresses

Two problems account for most production issues with conditional resources.

# Refactor aws_s3_bucket.logs -> count form without recreating it
moved {
  from = aws_s3_bucket.logs
  to   = aws_s3_bucket.logs[0]
}
  • Unknown count: The count value depends on resource attributes that cannot be determined until apply. Drive the toggle from a variable, or split the stack.
  • Index shifts: using count over a list means removing an item in the middle renumbers resources, causing destroy and recreate. Use for_each with stable keys for collections.
  • Toggling changes the address: moving from a plain resource to count turns aws_x.this into aws_x.this[0]. Without a moved block Terraform plans destroy and create.
  • Destroy on disable: flipping the toggle to false destroys the resource. Protect data with snapshots or prevent_destroy if that is unacceptable.
5️⃣

Production practice: module design and tests

Keep conditionals readable and verified.

  • One toggle per feature: expose a single boolean such as enable_flow_logs instead of scattering conditions across files.
  • Test both states: run terraform plan with the toggle on and off in CI, or use terraform test (1.6 and later) to assert counts.
  • Preconditions: use a precondition to fail early when a required companion variable is missing.
  • Prefer composition: if more than three or four resources share a condition, wrap them in a module and toggle the module.
  • Document defaults: state in the variable description whether the default creates the resource, because flipping a default in a shared module changes every caller's plan.
  • Interview angle: mention that you would rather expose a boolean and a clear module contract than let callers pass count directly, since count on module calls hides the toggle from readers.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Drive the toggle from an input variable (never from another resource's attribute) and reference the optional resource with <code>one(resource.name[*].attr)</code> so zero instances yield <code>null</code> instead of an index error."
⚡ 60-Second Elevator Pitch Talking Points
  • Terraform has no resource-level <code>if</code>, so I set <code>count</code> to 0 or 1, or <code>for_each</code> to an empty or single map, from a boolean variable.
  • I reference optional resources with <code>one(res[*].attr)</code> and test the plan with the toggle on and off.
  • I use <code>moved</code> blocks when changing the shape of a resource so toggling never recreates real infrastructure by accident.
⛔ 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. Basing <code>count</code> on a resource attribute created in the same apply The value is unknown at plan time, and Terraform refuses to plan; use a variable.
  2. Using <code>count</code> over a list that can be reordered Index renumbering recreates resources; use <code>for_each</code> with stable keys.
  3. Indexing <code>aws_x.this[0]</code> directly in outputs It errors when the count is zero; use <code>one()</code> or a splat expression.
  4. Adding <code>count</code> to an existing resource without a <code>moved</code> block The address changes to <code>[0]</code>, producing a destroy and create plan.
Advertisement
Want more Terraform & IaC scenarios?
Explore our complete collection of scenario-based Terraform & IaC interview runbooks.
Browse All Terraform & IaC Questions →