Collection Function

The Terraform collection function is a kind of built-in function that enables one to work with collections like lists, sets, and maps. It allows running several operations on these data structures, hence it provides easy manipulation and transformation of data in your Terraform configurations.

Types of Collection Functions

Terraform provides the following types of Collection functions:

1. alltrue Function

Alltrue in Terraform is a built-in function that will return true if all the elements in the given collection (lists, sets, or maps) are either true or the string "true". It also returns true if the collection happens to be empty. Syntax:
alltrue(list)
For example
terraform console
> alltrue([true,true])
true
> alltrue([true,false])
false
> alltrue(toset(["true","true"]))
true

2. anytrue Function

The anytrue function in Terraform takes a collection and evaluates every element in it. If at least one element is either true or "true", the function returns true. The function returns false if all elements are false or none of them have a value representing "true". If the collection is empty, the function also returns false. Syntax:
anytrue(list)
For example
terraform console
> anytrue([true,false])
true
> anytrue([false,false])
false
> anytrue([])
false

3. chunklist Function

The chunklist function takes a single input list and breaks it into fixed-size chunks, returning a list of those smaller lists. The syntax is
chunklist(list, chunk_size)
For example
terraform console
> chunklist(["a", "b", "c", "d", "e"], 2)
tolist([
    tolist([
        "a",
        "b",
    ]),
    tolist([
        "c",
        "d",
    ]),
    tolist([
        "e",
    ]),
])

4. coalesce Function

The coalesce function accepts any number of arguments and returns the first argument that is not null or an empty string. All arguments to the coalesce must be of the same type. The type of the return value of the coalesce function will be the same as the type of the arguments. Syntax
coalesce(argument1, argument2 ...)
For example
terraform console
> coalesce("terraform", "puppet")
"terraform"
> coalesce("", "puppet")
"puppet"
> coalesce(null, "puppet")
"puppet"
If the argument types are mismatched, Terraform will automatically convert them to the most general type that all of the arguments can convert to. If the types are incompatible and can't be converted, Terraform will emit an error. For example
terraform console
> coalesce(true, "terraform")
"true"
> coalesce(true, 23)
Call to function "coalesce" failed: all arguments must have the same type.

5. coalescelist Function

The coalescelist function takes any number of list arguments and returns the first list argument that is not empty. The syntax is
coalescelist(list1, list2 ...)
For example
terraform console
> coalescelist(["a", "b"], ["c", "d"])
[
    "a",
    "b",
]
> coalescelist([], ["c", "d"])
[
    "c",
    "d",
]

6. compact Function

The compact function takes one argument, which should be a list of strings and returns a new list containing only the original list's string elements excluding null or an empty string values. Syntax
compact(list)
For example
terraform console
> compact(["terraform", "", "puppet", null, "ansible"])
tolist([
    "terraform",
    "puppet",
    "ansible",
])

7. concat Function

The concat function combines two or more lists into a single list. The resulting list is made of all the elements from the original lists, in the order they were passed to the function. The syntax is
concat(list1, list2 ...)
For example
terraform console
> concat([1, 2, 3], [4, 5, 6], [7, 8, 9])
[
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
]

8. contains Function

The contains function checks if a given list contains a specified value as one of its elements. If the value is found, the function returns true. If the value is not found, the function returns false. The syntax is
contains(list, element)
For example
terraform console
> contains(["a", "b", "c"], "b")
true
> contains(["a", "b", "c"], "d")
false

9. distinct Function

The distinct function removes the duplicate elements in a list and returns a new list containing the remaining unique elements, in the order they first appeared. Syntax
distinct(list)
For example
terraform console
> distinct([1, 4, 2, 2, 1, 3])
tolist([
    1,
    4,
    2,
    3,
])

10. element Function

The element function returns a single element from within a list at a specified index. The syntax is
element(list, index)
The index used with the element function is zero-based that is, the first element in the list has an index of 0. The index must be a non-negative Integer. Negative or floating-point Integer indexes are not allowed. Utilizing the element function on an empty list will result in an error.
For example
terraform console
> element([1,2,3,4,5],2)
3
> element([1,2,3,4,5],-1)
Call to function "element" failed: cannot use element function with a negative index.
> element([1,2,3,4,5],0.3)
Call to function "element" failed: invalid index: value must be a whole number, between -9223372036854775808 and 9223372036854775807
> element([],3)
Call to function "element" failed: cannot use element function with an empty list.
If the given index is greater than the length of the list, the element function will "wrap around" the index by taking the index modulo (%) the length of the list. It then returns the value at the corresponding position.
terraform console
> element([1,2,3,4,5],7)
3
In this example, the function should return the element in index 2 whose value is 3 because of 7 % 5 = 2.

11. index Function

The index function returns the index of the first appearance of a specified value in a list. Its syntax is
index(list, value)
The index values start from 0 and increase step by step. If the value you are searching for does not occur in the list given to the index function, the function will raise an error.
For example
terraform console
> index([1,2,3,4,5],2)
1
> index([1,2,3,4,5],8)
Call to function "index" failed: item not found.

12. keys Function

The keys function takes a map as its argument and returns a list containing all the keys from that map. The keys in the resulting list are sorted in lexicographical (alphabetical) order. The syntax is
keys(map)
For example
terraform console
> keys({terraform: 1, puppet: 7, ansible: 4})
[
    "ansible"
    "puppet"
    "terraform"
]
> keys({configurations : {terraform: 1, puppet: 7, ansible: 4}, os: {linux: 78, windows: 90}})
[
    "configurations"
    "os"
]

13. length Function

Length function returns the length or size of a provided data structure like list, map, or string. The syntax is
length(string, str_character_set)
If you pass a list or a map to the length function, it'll return the number of elements in that collection. Example
terraform console
> length([1,2,3,4,5])
5
> length({terraform: 1, puppet: 7, ansible: 4})
3
If you pass a string to the length function, it returns the number of characters in that string. For example
terraform console
> length("terraform")
9

14. lookup Function

The lookup function retrieves the value of a single element from a map given its key. The syntax is
trimprefix(string, str_character_set)
Here is a breakdown of the syntax:
For example
terraform console
terraform console
> lookup({terraform: 1, puppet: 7, ansible: 4},"terraform", "no-key")
1
> lookup({terraform: 1, puppet: 7, ansible: 4},"diffkey", "no-key")
"no-key"

15. matchkeys Function

The matchkeys function constructs a new list which is a subset of elements taken from one list, where indexes of the selected elements match the corresponding indexes of values in another list. Syntax is
matchkeys(valueslist, keyslist, searchset)
Here is a breakdown of the syntax:
matchkeys identifies the indexes in keyslist that equal the elements of searchset, and makes a new list, using values in valueslist at those indexes. The ordering in valueslist is preserved in the result.
For example
terraform console
> matchkeys(["a", "b", "c"], ["x", "y", "z"], ["y", "z"])
tolist([
    "b",
    "c",
])

16. merge Function

The merge function in Terraform combines multiple map into a single map or multiple object into a single object. The function takes any number of arbitrary maps or objects and returns a new map or object that includes merged elements from all the arguments. The Syntax is
merge(map ...)
For example
terraform console
> merge({a = 1}, {b = 4})
[
    "a" = 1
    "b" = 4
]
If an input map or input object defines the same key or attribute more than once, then the value from the later input in the argument sequence takes precedence. For example
terraform console
> merge({a = 1, b = 2}, {b = 3, c = 4})
[
    "a" = 1
    "b" = 3
    "c" = 4
]

17. reverse Function

The reverse function in Terraform is used to reverse the order of elements in a sequence (list, tuple, or string). The syntax is
reverse(sequence)
For example
terraform console
> reverse([1,2,3,4,5])
[
    5,
    4,
    3,
    2,
    1,
]

18. setintersection Function

The Terraform setintersection calculates the intersection of multiple sets. It takes one or more sets as input and returns a single set which contains only elements present in all input sets. Syntax
setintersection(set ...)
For example
terraform console
> setintersection([1, 2, 3], [2, 3, 4])
toset[(
    2,
    3,
)]

19. setsubtract Function

The setsubtract function in Terraform calculates the relative complement of two sets. It takes two sets as input and returns a new set that contains elements from the first set that do not exist in the second set. The syntax is
setsubtract(a, b)
For example
terraform console
> setsubtract([1, 2, 3], [2, 3, 4])
toset[(
    1,
)]

20. setunion Function

The setunion terraform function calculates the union of multiple sets. This takes one or more sets as input, and returns a single set with all unique elements that exist in the input sets. The syntax is
setunion(set ...)
For example
terraform console
> setunion([1, 2, 3], [2, 3, 4])
toset[(
    1,
    2,
    3,
    4,
)]

21. slice Function

The Terraform slice function returns a subset of elements from an input list. It takes as input a list and two index values that return a new list comprising the elements of the original list that lie within the range specified by those indices. The syntax is:
slice(list, startindex, endindex)
The slice function extracts the elements from the list starting from the startindex (inclusive) up to, but not including, the endindex (exclusive).
terraform console
> slice([1, 2, 3, 4, 5], 1, 4)
[
    2,
    3,
    4,
]

22. sort Function

The sort function in Terraform sorts a list of strings in lexicographical order. Syntax is
sort(list)
For example
terraform console
> sort(["apple", "cherry", "banana", "date"])
tolist([
    "apple",
    "banana",
    "cherry",
    "date",
])

23. sum Function

The sum function in Terraform returns the total of all numbers in a given list or set. The syntax for this is:
sum(sequence)
It is worth pointing out that the sum function will fail if the input list or set is empty. This is because there are no numbers to sum, hence the function cannot return a meaningful result.
terraform console
> sum([])
Invalid value for "list" parameter: cannot sum an empty list.

24. transpose Function

The transpose function in Terraform flips the keys and values of a map of lists of strings and returns a new map of lists of strings. Syntax:
transpose(map)
For example
terraform console
> transpose({"key1" = ["value1", "value2", "value3"],"key2" = ["value4", "value5"],"key3" = ["value1", "value6", "value7", "value8", "value9"]})
tomap([
    "value1" = tolist([
        "key1",
        "key3",
    ]),
    "value2" = tolist([
        "key1",
    ]),
    "value3" = tolist([
        "key1",
    ]),
    "value4" = tolist([
        "key2",
    ]),
    "value5" = tolist([
        "key2",
    ]),
    "value6" = tolist([
        "key3",
    ]),
    "value7" = tolist([
        "key3",
    ]),
    "value8" = tolist([
        "key3",
    ]),
    "value9" = tolist([
        "key3",
    ]),
])

25. values Function

In Terraform, the values function retrieves the values from a map and returns them as a list. The values will be returned in lexicographical order. Syntax:
values(map)
For example
terraform console
> values({"key1" = "value1","key2" = "value2","key3" = "value3"})
[
    "value1",
    "value2",
    "value3",
]

26. zipmap Function

The zipmap function in Terraform is used to build a map from two lists: a list of keys and a corresponding list of values. The syntax is
zipmap(keyslist, valueslist)
The length of both lists used as an input must be the same. The keys list should include only strings, while the values can be any kind of data.
terraform console
> zipmap(["A", "B", "C"], [1, 2, 3])
{
    "A": 1
    "B": 2
    "C": 3
}
> zipmap(["A", "B", "C"], ["First", 2, true])
{
    "A": "First"
    "B": 2
    "C": true
}
If multiple instances of the same key, then only the value with the greatest index will be added to the resulting map. For instance
terraform console
> zipmap(["A", "B", "C", "A", "B"], [1, 2, 3, 4, 5])
{
    "A": 4
    "B": 5
    "C": 3
}

27. flatten Function

The flatten function in Terraform is used to flatten a nested list structure into a single, flattened list. The syntax is
flatten(list)
This function takes a list as an argument and checks every element in that list. If the element is a scalar value (not a list), it remains unchanged. However, if this element is a list, the function will "flatten" that nested list by replacing that with the individual elements of that list. It does the same thing recursively in the case where the nested list contains other lists. Example
terraform console
> flatten([["a", "b"], [], ["c"]])
[
    "a",
    "b",
    "c",
]

28. range Function

The range function returns a sequence of numbers. The syntax is
range(limit)
range(start, limit)
range(start, limit, step)
Here is the syntax breakdown:
For example
terraform console
> range(5)
tolist([
    0,
    1,
    2,
    3,
    4,
])
> range(1, 5)
tolist([
    1,
    2,
    3,
    4,
])
> range(1, 10, 2)
tolist([
    1,
    3,
    5,
    7,
    9,
])
> range(10, 5, -2)
tolist([
    10,
    8,
    6,
])

29. one Function

The one function in Terraform is used to handle situations where a list, set, or tuple value has either zero or one element. The syntax is
one(collection)
The one function returns null if the collection is empty. If the collection contains exactly one element, then the one function returns that element. However, if the collection has two or more elements, the one function will return an error.
terraform console
> one([1])
1
> one([])
null
> one([1,2])
Invalid value for "list" parameter: must be a list, set, or tuple value with either zero or one elements.

30. setproduct Function

The setproduct function in Terraform calculates the Cartesian product of the given sets. It takes one or more sets as input and returns all the possible combinations of elements from those sets. The basic syntax is
setproduct(sets ...)
For example
terraform console
> setproduct(["red", "green", "blue"], ["circle", "square", "triangle"])
tolist([
    [
        "red",
        "circle",
    ],
    [
        "red",
        "square",
    ],
    [
        "red",
        "triangle",
    ],
    [
        "green",
        "circle",
    ],
    [
        "green",
        "circle",
    ],
    [
        "green",
        "circle",
    ],
    [
        "blue",
        "circle",
    ],
    [
        "blue",
        "square",
    ],
    [
        "blue",
        "triangle",
    ],
])
The function will return an empty set if any of the input sets is empty. Such behavior is similar to that of the mathematical operation of the Cartesian product, whereby the product of any set against an empty set is an empty set. For example
terraform console
> setproduct(["red", "green", "blue"], [])
tolist([])
If all of the input sets have only a single element, the result of the function will also have only a single element, which is the combination of the first elements from each input set. This behavior is consistent with the mathematical definition of the Cartesian product, where the product of single-element sets is a set containing only the combination of those single elements. For example
terraform console
> setproduct(["red"], ["square"])
tolist([
    [
        "red",
        "square",
    ],
])

Related Pages

Feedback

Was this page helpful?