file to read file data, length to count elements in lists or maps, and toSet to convert lists into sets. However, we haven’t yet taken a closer look at how these functions process or transform values. Fortunately, Terraform’s interactive console allows you to test functions and interpolations before using them in your configurations.
For a safe and interactive testing environment, always validate changes in the console to prevent unexpected results in production.
Launching the Interactive Console
To start the interactive console, run:file, length, and toSet functions:
region list variable contains three elements. Note that using toSet with duplicate values (like “us-east-1”) automatically removes duplications because sets do not allow duplicates.
Terraform offers dozens of built-in functions to help you manage your configuration data. In the following sections, we’ll review some commonly used functions categorized by their use cases: numeric operations, string manipulation, collection processing, and map handling.
Numeric Functions
Numeric functions are useful for manipulating numerical values. For example, themax function returns the largest number among its arguments, while min returns the smallest. When working with sets or lists of numbers stored in a variable, you can use the expansion operator (...) to pass individual arguments.
Consider the following variable definition:
ceil: Rounds a number up to the nearest whole integer.floor: Rounds a number down to the nearest whole integer.
String Functions
String functions help with transforming and manipulating text data. One useful function issplit, which turns a string into a list based on a specified separator. For example, if you have a comma-separated string of AMI IDs, you can convert it into a list.
Here is a variable definition containing AMI IDs:
lower: Converts the string to lowercase.upper: Converts the string to uppercase.title: Converts the first character of each word to uppercase.
substr function extracts a substring by specifying an offset and a length. Note that indexes start at zero. For instance:
Collection Functions
Collection functions work with data types such as sets, lists, and maps. Thelength function, for example, returns the number of elements in a list. Consider this variable:
index: Finds the index of a specific element in a list.element: Retrieves the element at a particular index.contains: Checks if a list contains a specific element, returningtrueorfalse.
Remember that list indexing starts at zero, and the
contains function is case-sensitive.Map Functions
Map functions allow you to work with key-value pairs. Consider a variable where AMI IDs are stored in a map with regions as keys:keys and values functions:
lookup function. It takes the map and the key as arguments. If the key is missing, the function raises an error unless a default value is provided.
Example without a default value:
lookup function returns “ami-PQR” as the default value.