condition ? value_if_true : value_if_false.
Use conditional expressions to keep configuration DRY and to decide values dynamically during terraform plan and terraform apply.
Use conditional expressions to keep code clean and let Terraform compute configuration values (regions, SKUs, toggles) at plan/apply time.
for expressions and how they interact with conditional expressions and for_each.
Example showing provider, variable, and locals with a conditional:
- Nested
forexpression that returns a list of lists (nested list)
local.rg_nested becomes a list with inner lists (one per environment), for example:
[["rg-dev-api","rg-dev-web","rg-dev-db"], ["rg-prod-api","rg-prod-web","rg-prod-db"]].
- Single
forexpression with two iterators that returns a flat list
local.rg_flat produces a flat list:
["rg-dev-api","rg-dev-web","rg-dev-db","rg-prod-api","rg-prod-web","rg-prod-db"].
Using the generated names as resources
Terraform for_each supports maps and sets of strings. If you have a nested list (rg_nested), flatten it before converting to a set. Example using the nested list:
rg_flat), you can use it directly:
flatten, for_each will fail during terraform plan:
for expression produced a list that contains inner lists. flatten() converts a nested list into a single flat list, which toset() can then convert into a set of strings acceptable to for_each.
If you produce nested lists, call
flatten() before toset() when using for_each. Otherwise Terraform will complain that the argument type is not a set of strings.environment = "dev", local.location will compute to "westus", so all resource groups are planned for West US. Example plan (after using flatten or rg_flat):
local.location evaluates to "eastus" and the plan shows East US locations:
Summary
- Conditional expressions are Terraform’s ternary operator — useful for environment-specific values and small toggles.
forexpressions build lists. Use a doubleforto produce a flat list directly, or nestforexpressions to create grouped lists.- If you have nested lists, use
flatten()beforetoset()sofor_eachreceives a set of strings. - Override variables at
plan/applytime (e.g.,-var='environment=prod') to affect computed locals likelocal.location.