terraform: Append to a list using concat

2 min read | by Jordi Prats

To be able to conditionally append objects (or strings) to a list in terraform we must put it in another way: How do we dynamically generate a list of objects?

The answer is using we can use the concat() function

result = concat(["A"], ["B"])

The concat() function will merge any set of lists. The trick here is to conditionally merge empty lists if needed to get the list we want, for example:

conditional_append = concat(var.set_a ? ["A"]:[], var.set_b ? ["A"]:[])

Using this code if we set:

set_a = false
set_b = false

We will get an empty array:

      ~ conditional_append = []

By setting one of them to true:

set_a = true
set_b = false

The resulting list will have just one item:

      ~ conditional_append = [
          + "A",
        ]

Finally, by setting both to true:

set_a = true
set_b = true

We will be getting both strings on a list as expected:

      ~ conditional_append = [
          + "A",
          + "B",
        ]

Posted on 24/12/2020

Categories