'Terraform split/join/list
I recently found the following line of terraform in our code (some values sanitized):
subnet_ids = [ "${split(",", var.xxx_lb ? join(",", data.yyy_ids.private.ids) : join(",", concat(data.yyy_ids.public.ids, list(""))))}" ]
I'm trying to understand why code would be written this way. More specifically, what is the final join doing? Pulling it out for clarity:
join(",", concat(data.yyy_ids.public.ids, list("")))
It seems that someone (no longer at the company) was trying to ensure that a non-empty list is returned. We definitely don't want the empty ("") item in the list.
So, the questions here are:
- What logically is going on in this statement?
- Is there a better way?
- If there is not a better way, how can we remove the empty entry from the resulting list?
Solution 1:[1]
What logically is going on in this statement?
The original author attempts to create a list with the subnet ids
a) The first split statement will take a string in this case the subnet ids and return them as a list, by splitting them based on the delimiter ,
var.xxx_lb ? clause_if_true : clause_if_false
b) Next terraform will evaluate this variable as a boolean and according to the result you will get the public or the private subnet ids, by employing the ternary operator syntax
join(",", data.yyy_ids.private.ids)
c) In case the boolean value is true, terraform will examine this part
This will return a string by joining the items of the list.
And add the delimeter ,. I assume the reason that he attempts to join them as a string is to be accordance with the section a)
join(",", concat(data.yyy_ids.public.ids, list("")))
d) If the boolean value in b) evaluates to false terraform will examine this part.
The concat function takes as input lists and returns them as a single list.
And then performs the same logic as in c)
The list function is deprecated, tolist should be used instead.
Is there a better way?
I would employ a straight forward way. Check the boolean value, if it is true get the list with private ids. If false the public ones.
subnet_ids = var.xxx_lb ? data.yyy_ids.private.ids : data.yyy_ids.public.ids
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
