How to remove values from a map in Terraform that match a key value

Viewed 8076

I have a sample map like below and am trying to remove any accounts that have a key2 value matching 'bong'.

So the starting map would look like this:

sample_map={
  account1 = {
      key1       ="foo"
      key2       ="bar"
  }
  account2 = {
      key1       ="bing"
      key2       ="bong"
  }
}

And the end result should look like this:

new_map={
  account1 = {
      key1       ="foo"
      key2       ="bar"
  }
}

I've tried manipulating the following for loop but it only works if var.exclude matches the label (not a key).

new_map = { for k, v in var.sample_map : k => v if ! contains(var.exclude, k) }
1 Answers

You were almost there, if I understand correctly. It should be:

contains(values(v), var.exclude)

The working example is below:


variable "sample_map" {

  default ={
    account1 = {
        key1       ="foo"
        key2       ="bar"
    }
    account2 = {
        key1       ="bing"
        key2       ="bong"
    }  
  }
}

variable "exclude" {
  default = "bong"
}


output "test" {
  value = { for k, v in var.sample_map: k => v if ! contains(values(v), var.exclude) }
}

Which gives:

test = {
  "account1" = {
    "key1" = "foo"
    "key2" = "bar"
  }
}
Related