Bitzu

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

Single choice

How can you add a custom function to a Terraform configuration?

  1. Declare it with a function block
  2. You cannot define functions in the configuration language
  3. Put it in a locals block as a lambda
  4. 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).

Select all that apply

Which statements about built-in functions are correct?

  1. lookup(map, key, default) returns the default when the key is missing
  2. merge combines several maps into one
  3. concat joins lists into a single list
  4. join returns a list of the pieces it was given
  5. 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

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.

Download on the App StoreGet it on Google Play

More Terraform Associate 004 topics in this module