Lesson 1 of 3 Expressions and Functions

Conditional, for and Splat Expressions

Expressions compute values from other values. This lesson covers conditional expressions, for expressions and splat expressions, the building blocks of dynamic configuration.

Learning outcomes

After completing this lesson, you will be able to:

  • Interpret conditional, for and splat expressions.
  • Explain how to convert collections for use with for_each.

Conditional expressions

A conditional expression chooses between two values: CONDITION ? TRUE_VALUE : FALSE_VALUE. The condition must be a bool, and both results should be of the same type, or of types Terraform can convert to a common one.

locals {
  is_prod       = var.environment == "prod"
  instance_type = local.is_prod ? "m6i.large" : "t3.micro"
  backup_count  = local.is_prod ? 1 : 0
}

Conditionals often drive count for optional resources, as with backup_count. Comparison operators are ==, !=, <, >, <= and >=, and logical operators are &&, || and !.

Fill in the number

Evaluating conditionals

Exam skills 4.5.1

Evaluate conditional expressions that drive configuration.

Log in to try this activity Interactive activities are free with an account.

for expressions

A for expression creates a new collection by transforming each element of another. Square brackets produce a list (tuple); braces with => produce a map (object). An optional if clause filters elements.

variable "users" {
  type = list(object({ name = string, admin = bool }))
}

locals {
  upper_names = [for u in var.users : upper(u.name)]
  admins      = [for u in var.users : u.name if u.admin]
  by_name     = { for u in var.users : u.name => u }
  tag_pairs   = [for k, v in var.tags : "${k}=${v}"]
}

When the input is a list, a two-symbol form for i, u in var.users gives the index and the element; when it is a map, for k, v in var.tags gives the key and the value. If a map result could have duplicate keys, add the grouping symbol ... after the value to collect duplicates into lists. A common use is turning a list into a map for for_each, such as by_name above.

The following diagram shows a for expression turning a list of objects into a map for for_each.

Turning a list of objects into a map for for_each. A list of objects is neither a map nor a set of strings, so for_each rejects it. A for expression with braces and => builds a map keyed by name; instances are then addressed as aws_subnet.this[“app”] and each.value.cidr reads the CIDR. Names must be unique.
The sample values are illustrative.
Scenario questions

Reading for expressions

Exam skills 4.5.1

Predict the result of for expressions.

Log in to try this activity Interactive activities are free with an account.

Splat expressions

The splat operator [*] is shorthand for a simple for expression over a list: var.users[*].name is the same as [for u in var.users : u.name]. It is used most often with count resources, as in aws_instance.web[*].private_ip. Splat does not work directly on maps, including resources that use for_each; use values() or a for expression for those.

Conditional
PurposeChoose one of two values
Examplea ? b : c
ResultOne value
for expression
PurposeTransform and filter a collection
Example[for x in l : f(x) if g(x)]
ResultA list or a map
Splat
PurposePick one attribute from each list element
Examplel[*].id
ResultA list
Worked example

Building a map for for_each

A variable is a list of objects, each with a name and a CIDR block. A developer writes for_each = var.subnets and gets an error that for_each requires a map or a set of strings.

The decisive fact is the type for_each accepts.

A list of objects is neither a map nor a set of strings. Converting it with for_each = { for s in var.subnets : s.name => s } creates a map keyed by name, so instances are addressed as aws_subnet.this["app"] and each.value.cidr reads the CIDR. The names must be unique, or the map would have duplicate keys and Terraform would report an error.

Check yourself

What does { for u in var.users : u.name => u.email } produce?

Show answer

A map from each user's name to their email address; braces with => produce a map.

Exam Tips

Remember for the exam

  • cond ? a : b; both results should share a type.
  • [for ...] gives a list; {for ... => ...} gives a map; if filters.
  • [*] is a shorthand for lists only.