Collection Functions
Abhishek Anand Amralkar
Posted on July 31, 2020
The next in line is TF Collection Functions and they are very useful in day to day use for writing TF code.
- concat
concat
functions take 2 lists as an input and returns a new list.
concat(aws_vpc_endpoint.sts.*.id, [""])[0]
- contains
contains
functions checks for the element in the given list or set and returns a boolean.
contains(["a", "b", "c"], "a")
true
- element
element
functions return the item from the list given the index
element(var.azs, count.index)
The above code will return an availability zone
at index start with count.index
usually start from 0 and so on depending upon the count you set.
- flatten
flatten
takes a list and replaces any elements that are lists with a flattened sequence of the list contents.
flatten(module.nginx.vpc_security_group_ids)
With the above code, we can flatten the list of lists.
- map
map
takes an even number of arguments and returns a map whose elements are constructed from consecutive pairs of arguments.
map('BusinessUnit','XYZ')
- merge
merge
takes an arbitrary number of maps and returns a single map that contains a merged set of elements from all of the maps.
If more than one given map defines the same key then the one that is later in the argument sequence takes precedence.
tags = merge(
{
"Name" = format("%s-%03d-%s", var.namespace, count.index, var.environment)
},
var.tags,
)
volume_tags = merge(
{
"Name" = format("%s-%03d-%s", var.namespace, count.index, var.environment)
},
var.volume_tags,
)
In the above code, we are merging all maps and passing them as a single map.
The above listed functions are few of the many Collection Functions Terraform have and are opiniaoted depending on my usage.
Posted on July 31, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.