Conditionals and for expressions
Use the ternary operator to switch resources on and off, and for expressions to filter, reshape and group lists and maps, with the traps each one sets.
Conditionals and for expressions
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- HCL has one conditional, `condition ? true_value : false_value`. Both branches must produce a compatible type.
- `count = var.enabled ? 1 : 0` is the idiom for an optional resource. It is how 27 resources in the popular AWS VPC module are switched.
- A for expression builds a list with `[for x in xs : f(x)]` or an object with `{for k, v in m : key => value}`, with an optional `if` filter.
- Building an object with duplicate keys is an error unless you add `...` to group the values into lists.
- The splat form `aws_instance.web[*].id` is shorthand for a simple for expression over every instance.
Logic without a programming language
You want a monitoring module that creates an alarm only when enable_alarms is true, and that turns a map of services into a list of alarm names. HCL is a configuration language and has no if statement and no for loop. It has expressions that give you the same results, which keeps configurations declarative: every value is computed from other values, with nothing that runs in sequence.
Two tools cover most needs: the conditional operator and the for expression.
The conditional
condition ? value_if_true : value_if_false
Written from the Terraform docs. I did not run any of the HCL in this lesson. The condition must be a boolean, and both results should have a compatible type. Terraform tries to convert them to one type, and errors if it cannot, so x ? "a" : 5 is a mistake while x ? "a" : "b" is not.
Two uses cover almost everything:
- Choosing a value:
instance_type = var.environment == "prod" ? "m7g.large" : "t4g.small". - Switching a resource on or off: put the condition in
count:
resource "aws_cloudwatch_metric_alarm" "cpu" {
count = var.enable_alarms ? 1 : 0
# ...
}
When count is 0 the resource does not exist. When it is 1 it exists as aws_cloudwatch_metric_alarm.cpu[0]. The brackets are the cost. Anything that refers to it has to deal with a list that may be empty. The one() function turns a zero-or-one list into the single value or null.
How common is the idiom? I counted it in the AWS VPC module’s main.tf:
$ grep -c 'count *= .*? 1 : 0' main.tf
27
27 resources in that one file are optional through exactly this pattern. Once you recognise it, big public modules get much easier to read.
For expressions
A for expression builds a new collection from an old one. The square brackets make a list, and curly braces make an object.
To see the behaviour, I wrote the equivalents in Python and ran them on a small map of users. This is Python standing in for the HCL form named on each line, not Terraform output:
[for k,v in users : upper(k)] -> ['ANA', 'BO', 'CY']
[for k,v in users : k if v.admin] -> ['ana']
{for k,v in users : k => v.team} -> {'ana': 'web', 'bo': 'web', 'cy': 'data'}
{for k,v in users : v.team => k...} -> {'web': ['ana', 'bo'], 'data': ['cy']}
same without the '...' grouping -> ERROR Duplicate key 'web'
The shapes:
[for x in xs : f(x)]maps every element.[for k, v in m : k if v.admin]adds anifclause that filters.{for k, v in m : key => value}builds an object. Keys must be unique strings....after the value groups colliding keys into lists, instead of an error.
A real one, from the same VPC module: for_each = { for k, v in var.vpc_block_public_access_exclusions : k => v if local.create_vpc }. It copies a map and filters it with the same condition used for count elsewhere, so for_each receives an empty map when the VPC is switched off.
The splat shortcut
When a resource has several instances because of count, aws_instance.web[*].id collects an attribute from each into a list. It is shorthand for a for expression. Use it for the simple case and write the full form when you need to filter or reshape.
Traps
- Unknown values in
countandfor_each. Terraform must know how many instances there are at plan time. Thefor_eachdocs say keys must be known before apply, and that sensitive values cannot be used. A condition based on a resource attribute that only exists after apply will fail. - Complexity creep. A for expression inside a ternary inside a function call is correct and unreadable. Break it into
locals, which you met two lessons back, and name the pieces. - Reaching through an empty list. After
count = 0,aws_x.name[0].idis an error. Guard it with the same condition, or useone(). - Types of empty branches.
var.on ? [var.x] : []is fine, and is the standard way to produce an optional list item.
The line to draw
Conditionals and loops can make a configuration do almost anything, and that is the risk. If a module needs five nested conditions to work, it probably is two modules. The dynamic block and for_each give you repetition in a more structured form: count and for_each comes after built-in functions.
About the video
The embed is most of Anton Putra’s “Terraform Tips & Tricks: loops, if-statements, and more”, April 2023, from “Loops” to the end (1:10 to 27:20). It has only two chapters, so I could not check that it covers for expressions specifically. The title and chapters promise loops and conditionals, and the examples are AWS. It is 26 minutes, and its loops section is about 20 of them. English was judged from title, channel and an English caption track. It predates Terraform 1.9, though nothing in this lesson needed anything newer. The Piyush video in deeper has separate conditional and splat chapters.
Where this fits
Expressions call functions all the time. Next, the ones you will actually use, and how to try them without applying anything: built-in functions in practice.
Check yourself
You want a resource created only in production. What do you write?
`count = var.environment == "prod" ? 1 : 0` on the resource. Elsewhere you then refer to it as `aws_x.name[0]`, or with `one()`, since it is now a list.
What does `{ for k, v in var.users : v.team => k }` do when two users share a team?
It fails with a duplicate key error. Add `...` after the value, `v.team => k...`, to group the keys into a list per team.
Why is `var.enabled ? "a" : 5` a problem?
The two branches have different types. Terraform tries to unify them, converting where it can, and fails when it cannot. Keep both branches the same type.
How do you pick only the admins from a map of users into a list of names?
`[for name, u in var.users : name if u.admin]`. The `if` clause filters, and the expression before it picks what to output.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.