Terraform has no if statement. It has one conditional expression, the ternary operator:
condition ? true_val : false_val
Everything conditional in Terraform comes from three things: this expression, null meaning "omit", and iterating zero or one times. This page shows how they combine.
The basics¶
locals {
sku = var.environment == "prod" ? "P1v3" : "B1"
replicas = var.high_availability ? 3 : 1
name_suffix = var.suffix != "" ? "-${var.suffix}" : ""
}
conditionmust evaluate tobool. The strings"true"/"false"convert automatically; anything else errors.- Only the chosen branch is evaluated. That's what makes the ternary the safe way to guard against nulls (see null-safe access).
- If the condition is unknown at plan time, the result is unknown.
Readability rules¶
- One ternary per expression. Nested ternaries are legal but painful:
```hcl # ❌ hard to read and review sku = var.env == "prod" ? "P2v3" : var.env == "test" ? "P1v3" : "B1"
# ✅ a lookup map says the same thing and is easier to extend sku = lookup({ prod = "P2v3", test = "P1v3" }, var.env, "B1")
# ✅ even better: make it an input with per-environment tfvars sku = var.app_service_sku ```
-
Decide on capabilities, not environment names.
var.environment == "prod" ? ...inside a module means the module has to change every time someone adds an environment. Exposevar.zone_redundantand let the caller decide. This is the most common design smell in Terraform; see multi-environment configuration. -
Name complex conditions with a local.
```hcl locals { needs_private_endpoint = var.public_network_access == false && var.subnet_id != null }
resource "azurerm_private_endpoint" "this" { count = local.needs_private_endpoint ? 1 : 0 # ... } ```
Type unification¶
Both branches must have, or be convertible to, a common type. This is the main source of ternary errors.
# ✅ number vs number
var.ha ? 3 : 1
# ✅ string vs number → both become string
var.x ? "auto" : 5
# ✅ list vs empty tuple → list(string)
var.extra ? ["10.0.0.0/24"] : []
# ❌ "Inconsistent conditional result types": two object types with different attributes
var.custom ? { sku = "P1v3", tier = "Premium" } : {}
# ✅ Fix 1: make both branches the same shape
var.custom ? { sku = "P1v3", tier = "Premium" } : { sku = null, tier = null }
# ✅ Fix 2: when it's really a map, convert explicitly
var.custom ? tomap({ sku = "P1v3", tier = "Premium" }) : tomap({})
# ✅ Fix 3: return null and handle it downstream
var.custom ? { sku = "P1v3", tier = "Premium" } : null
null unifies with any type, so cond ? something : null always type-checks.
Conditional resources¶
To create a resource only sometimes, give it zero or one instance.
With count¶
resource "azurerm_monitor_diagnostic_setting" "this" {
count = var.log_analytics_workspace_id != null ? 1 : 0
name = "diag-${var.name}"
target_resource_id = azurerm_key_vault.this.id
log_analytics_workspace_id = var.log_analytics_workspace_id
enabled_log { category_group = "allLogs" }
}
# Referencing it: it's a list now, so handle the empty case
output "diagnostic_setting_id" {
value = one(azurerm_monitor_diagnostic_setting.this[*].id) # null when count = 0
}
one() returns the single element, or null for an empty list, and errors if there's more than one. It's the cleanest way to read a conditional resource. The older idiom length(x) > 0 ? x[0].id : null does the same thing with more noise.
With for_each¶
resource "azurerm_management_lock" "this" {
for_each = var.lock_level != null ? { (var.lock_level) = true } : {}
name = "lock-${var.name}"
scope = azurerm_resource_group.this.id
lock_level = each.key
}
count = cond ? 1 : 0 is clearer for a plain on/off switch. Use for_each when the single instance's key is meaningful.
With enabled (OpenTofu 1.11+)¶
OpenTofu adds an enabled meta-argument that expresses on/off directly and keeps the resource address singular (no [0]):
# OpenTofu 1.11+ only
resource "azurerm_management_lock" "this" {
lifecycle {
enabled = var.lock_level != null
}
# ...
}
Check the OpenTofu docs for the exact placement in your version. Terraform doesn't have it; use count for portable modules.
Changing an existing resource to conditional¶
Adding count to an existing resource changes its address from azurerm_x.this to azurerm_x.this[0], and Terraform will plan destroy-and-recreate. Add a moved block in the same change:
moved {
from = azurerm_key_vault.this
to = azurerm_key_vault.this[0]
}
More in state refactoring.
Conditional modules¶
Modules accept count and for_each too:
module "bastion" {
source = "../modules/bastion"
count = var.enable_bastion ? 1 : 0
subnet_id = module.network.subnet_ids["AzureBastionSubnet"]
}
output "bastion_host_name" {
value = one(module.bastion[*].host_name)
}
A module whose count is driven by a value only known after apply won't plan. Keep the toggle an input.
Conditionally omitting an argument¶
Setting an argument to null is identical to not writing it, so the provider's default applies:
resource "azurerm_linux_web_app" "this" {
# ...
virtual_network_subnet_id = var.integration_subnet_id # null → no VNet integration
client_certificate_mode = var.require_client_cert ? "Required" : null
}
Prefer null over inventing a "default" value yourself. If you write var.x ? "Required" : "Optional", you've now hard-coded the provider default, and if it changes your plan won't reflect the provider's intent.
Conditional nested blocks¶
Nested blocks can't be assigned null. Use a dynamic block that iterates zero or one times:
resource "azurerm_storage_account" "this" {
# ...
dynamic "network_rules" {
for_each = var.network_rules != null ? [var.network_rules] : []
content {
default_action = network_rules.value.default_action
ip_rules = network_rules.value.ip_rules
virtual_network_subnet_ids = network_rules.value.subnet_ids
}
}
}
The splat shorthand does the same thing because null[*] is [] and a single object [*] is a one-element list:
dynamic "network_rules" {
for_each = var.network_rules[*]
content { /* ... */ }
}
Conditional items in collections¶
locals {
# Conditionally include list items
allowed_ips = concat(
var.office_ips,
var.allow_vpn ? [var.vpn_ip] : [],
)
# Conditionally include map entries
tags = merge(
var.tags,
var.cost_center != null ? { cost_center = var.cost_center } : {},
)
# Filter with a for expression
public_subnets = { for k, s in var.subnets : k => s if s.public }
# Drop nulls and empty strings from a list
dns_servers = compact([var.primary_dns, var.secondary_dns])
}
Null-safe access¶
Reading an attribute of something that might be null:
# Ternary guard: only evaluates the attribute when var.backup is set
retention = var.backup != null ? var.backup.retention_days : 7
# try(): evaluate, fall back on any error
retention = try(var.backup.retention_days, 7)
# coalesce(): first non-null, non-empty value
location = coalesce(var.location, data.azurerm_resource_group.this.location)
# lookup() with default for maps
sku = lookup(var.skus, var.environment, "B1")
try() is concise but swallows every error, including typos in attribute names. Prefer the explicit ternary in modules where silent fallbacks would hide bugs, and save try() for genuinely dynamic data (decoded JSON/YAML).
coalesce() skips both null and "", and all its arguments must convert to one common type.
Conditionals in templates¶
Inside strings, use the %{ if } directive:
user_data = <<-EOT
#!/bin/bash
%{ if var.install_agent ~}
curl -sL https://example.com/agent.sh | bash
%{ endif ~}
echo "done"
EOT
See expressions.
Conditionals in validation and lifecycle conditions¶
variable "sku" {
type = string
validation {
condition = var.zone_redundant ? startswith(var.sku, "P") : true
error_message = "Zone redundancy requires a Premium (P*) SKU."
}
}
The pattern A ? B : true reads as "if A then B must hold". It's logical implication, which Terraform has no operator for. !A || B is the equivalent boolean form.
When not to use a ternary¶
| Situation | Better tool |
|---|---|
| Value differs per environment | A variable with per-env tfvars (environments) |
| Many values switch together (small/medium/large) | A lookup map of tier objects |
| Three or more branches | lookup() on a map, or a map index |
| Behaviour differs fundamentally | Two modules, or a composition module that wires different children |
| You're toggling a whole resource | count = cond ? 1 : 0 (or enabled in OpenTofu) |