terraform: one() function to retrieve the only element of a list

1 min read | by Jordi Prats

On the terraform 0.15 CHANGELOG we can see that they have added the one function. This function is intended to simplify existing code, improving it's readability and further smoothen the terraform learning curve

This function takes as input a list, set or tuple with one or zero elements on it. If there are two or more elements then one will return an error. If the collection is empty it returns a null, otherwise returns the first (and only) element.

It comes really handy when we have conditionally included resources

So, starting from terraform 0.15 we can change the following code:

length(var.foo) != 0 ? var.foo[0] : null

To this:

one(var.foo)

At the end of the day, the code means the same but many code analysis tools put it: "reduces cognitive complexity" Meaning that feels simpler to understand


Posted on 20/05/2021

Categories