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
Which form is the correct syntax of a conditional expression in Terraform?
- if var.on then 1 else 2
- var.on ? 1 : 2
- var.on : 1 ? 2
- 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.
Which statements about for expressions are correct?
- An if clause can filter out elements, so the result may be shorter than the input
- Square brackets produce a tuple-like result
- Curly braces produce an object and need => between key and value
- A for expression modifies the source collection in place
- 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: 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.
