DEV Community

drewmullen
drewmullen

Posted on • Edited on

Terraform: Delete an Item from a List

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)

Collapse
 
bigfantech profile image
bigfantech

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]

Collapse
 
mgoldbas profile image
Maxwell Goldbas

updated for terraform > v0.12

echo 'compact([for x in tolist([1 ,2 ,3 ,4 ,5]) : x == 2 ? "" : x])' | terraform console

Collapse
 
drewmullen profile image
drewmullen

Updated! thank you!