I recently used setsubtract to solve a buggy terraform pipeline. In short I needed to remove the listitem "latest". The problem was the new list afterwards I could not reference item 0 in the list. I am not sure why because using terraform output to check the two lists they look good. Adding a typecast tolist() worked though.

code

❯❯ cat variables.tf 
locals {
  images = ["1", "latest", "2"]
  remove_list = ["latest"]
  # need tolist here: https://github.com/hashicorp/terraform/issues/23882
  image_list = tolist(setsubtract(local.images , ["latest"]))
}

output orig_list {
  value = local.images
}

output new_list {
  value = local.image_list
}

output images_0 {
  value = local.image_list[0]
}

check it

❯❯ terraform plan

Changes to Outputs:
  + images_0  = "1"
  + new_list  = [
      + "1",
      + "2",
    ]
  + orig_list = [
      + "1",
      + "latest",
      + "2",
    ]

Previous Post