Bitzu

Terraform Associate 004 ยท Dynamic configuration

Conditionals, for expressions and splat in HCL

Ternary conditional, for expressions over lists and maps, splat [*], string interpolation and templates (4e).

Key points

  • A conditional is condition ? true_val : false_val and both branches must resolve to a compatible type.
  • A for expression transforms a collection: [for x in list : f(x)] builds a tuple, { for x in list : key => val } builds an object, and an optional if clause filters.
  • A splat, list[*].attr, is shorthand for a simple for expression over lists, sets and tuples.

Source: https://developer.hashicorp.com/terraform/language/expressions/for

Practice questions

Single choice

Which form is the correct syntax of a conditional expression in Terraform?

  1. if var.on then 1 else 2
  2. var.on ? 1 : 2
  3. var.on : 1 ? 2
  4. var.on && 1 || 2
Show answer

Answer: B. var.on ? 1 : 2

Terraform uses the C-style ternary: the condition, a question mark, the value for true, a colon, then the value for false. The other forms are not HCL syntax.

Select all that apply

Which statements about for expressions are correct?

  1. An if clause can filter out elements, so the result may be shorter than the input
  2. Square brackets produce a tuple-like result
  3. Curly braces produce an object and need => between key and value
  4. A for expression modifies the source collection in place
  5. Duplicate keys in an object result are silently merged
Show answer

Answer: A. An if clause can filter out elements, so the result may be shorter than the input, B. Square brackets produce a tuple-like result, C. Curly braces produce an object and need => between key and value

Square brackets yield a tuple, curly braces with => yield an object, and an if clause can drop elements. A for expression never changes its source, and object keys must be unique unless grouping mode (...) is used.

True or false

True or false: the splat expression aws_instance.web[*].id can be used on a resource created with for_each.

Show answer

Answer: False

False. Splat expressions work on lists, sets and tuples. A resource using for_each is a map of instances, so use a for expression such as [for i in aws_instance.web : i.id], or values().

Practice 8 questions on this topic in Bitzu

Short lessons, instant explanations and spaced review of what you get wrong. Free on iOS and Android.

Download on the App StoreGet it on Google Play

More Terraform Associate 004 topics in this module