Terraform · Infrastructure as code

How do conditionals work in Terraform?

MediumconditionalsternaryexpressionsUpdated Oct 2026
Quiz this track

Short answer

Terraform conditionals are ternary expressions, and booleans can drive count to include or exclude a resource. Keep conditions shallow and move named decisions into locals for readability.

The conditional expression has the form condition ? true_value : false_value. It is an expression, not a statement, so it can appear in any argument. Both branches must have compatible types, even if only one is selected at runtime.

hcl
locals {
  is_prod       = var.environment == "prod"
  instance_type = local.is_prod ? "m6i.large" : "t3.micro"
  backup_days   = local.is_prod ? 30 : 7
}
Named booleans make the production decision visible and reusable.

Common patterns

  • Select a value with a ternary expression
  • Enable a resource with count = condition ? 1 : 0
  • Use for_each with an empty map to disable a set of resources
  • Combine conditionals with contains and lookup for policy choices

Deeply nested ternaries are hard to review and easy to get wrong. Break them into locals with names, or use a lookup map keyed by environment. Remember that conditionals do not skip expression evaluation; an invalid reference in an unused branch can still cause an error.

Do not build strings like "true" or "false" and compare them. Use real booleans so the type system and validation can help.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How do you conditionally create a resource?
  2. 2Why can an unused branch still cause an error?
  3. 3How do you avoid deeply nested ternaries?
  4. 4Can conditionals change a resource's type?

Say it in the interview

Terraform conditionals are ternary expressions, so they work anywhere an expression is allowed. I usually name the boolean in a local, such as is_prod, and derive instance size or backup retention from it. To create or skip a resource I use count with zero or one. I avoid deep nesting and remember that both branches are still type-checked and evaluated for references.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.