I had a need to remove an expected item from a list recently while working with terraform. surprisingly, there is no native function to do that. The snippet below removes 2
from the list:
compact([for x in tolist(1 ,2 ,3 ,4 ,5) : x == 2 ? "" : x])
Try it for yourself!
echo 'compact([for x in tolist([1 ,2 ,3 ,4 ,5]) : x == 2 ? "" : x])' | terraform console
Update
Thanks to @goldbas for mentioning the list()
was deprecated.
Top comments (3)
There is a function to do this: setsubtract()
setsubtract([1 ,2 ,3 ,4 ,5], [2])
Output: [1, ,3 ,4 ,5]
other option: comparing to other answers, loop can be done better like this
[ for v in [1 ,2 ,3 ,4 ,5] : v if v != "2"]
Output: [1, ,3 ,4 ,5]
updated for terraform > v0.12
echo 'compact([for x in tolist([1 ,2 ,3 ,4 ,5]) : x == 2 ? "" : x])' | terraform console
Updated! thank you!