Terraform Associate 004 ยท Dynamic configuration
Built-in functions and terraform console
Using functions such as lookup, merge, concat, join, format, length, toset, file, cidrsubnet; terraform console to test; no user-defined functions (4e).
Key points
- Terraform ships built-in functions called as name(args), for example lookup, merge, concat, join, format, length, toset, file and cidrsubnet.
- You cannot define your own functions in configuration.
- To experiment, run terraform console and type expressions; it evaluates them against the current state and configuration without changing infrastructure.
Source: https://developer.hashicorp.com/terraform/language/functions
Practice questions
How can you add a custom function to a Terraform configuration?
- Declare it with a function block
- You cannot define functions in the configuration language
- Put it in a locals block as a lambda
- Write it in a variable's default value
Show answer
Answer: B. You cannot define functions in the configuration language
The configuration language has no syntax for user-defined functions; only the built-in set is available (providers can expose their own functions, but you cannot write one in HCL).
Which statements about built-in functions are correct?
- lookup(map, key, default) returns the default when the key is missing
- merge combines several maps into one
- concat joins lists into a single list
- join returns a list of the pieces it was given
- length cannot be used on maps
Show answer
Answer: A. lookup(map, key, default) returns the default when the key is missing, B. merge combines several maps into one, C. concat joins lists into a single list
lookup returns a default when the key is missing, merge combines maps, and concat joins lists. join produces a string from a list, not a list, and length also works on maps.
True or false: lookup({a = "ay"}, "c", "what?") returns null because key c does not exist.
Show answer
Answer: False
False. When the key is missing, lookup returns the third argument, here "what?". Without a default it behaves like plain map[key] indexing.
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.
