Q: How do you handle conditionally creating a resource in Terraform?
Use count:
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.
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 : 0is the simplest and most common form. The resource is then addressed asaws_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:
countandfor_eachonmoduleblocks 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
countfor a simple on or off switch, andfor_eachwhen you manage a collection or want a stable key that appears in the state address and in plan output.
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 returnsnullwhen 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 preferone(). - Output: publish the nullable value as a module output so callers can handle absence explicitly.
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
nullto omit it, for examplekms_key_id = var.kms_key_arnwith anulldefault. - Optional nested block: use a
dynamicblock 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
validationblock so dependent variables (like a certificate ARN when HTTPS is on) cannot be left unset.
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
countover a list means removing an item in the middle renumbers resources, causing destroy and recreate. Usefor_eachwith stable keys for collections. - Toggling changes the address: moving from a plain resource to
countturnsaws_x.thisintoaws_x.this[0]. Without amovedblock Terraform plans destroy and create. - Destroy on disable: flipping the toggle to false destroys the resource. Protect data with snapshots or
prevent_destroyif that is unacceptable.
Production practice: module design and tests
Keep conditionals readable and verified.
- One toggle per feature: expose a single boolean such as
enable_flow_logsinstead of scattering conditions across files. - Test both states: run
terraform planwith the toggle on and off in CI, or useterraform test(1.6 and later) to assert counts. - Preconditions: use a
preconditionto 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.
- 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.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- 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.
- Using <code>count</code> over a list that can be reordered Index renumbering recreates resources; use <code>for_each</code> with stable keys.
- 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.
- 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.