Filter a map using a list of keys to create a new map

Hi there…I have a terraform map object that looks like this

all_subnets = {
    "10.1.1.1"  = "subnet-a"
    "10.2.2.2" = "subnet-b"
    "10.3.3.3"  = "subnet-c"
    "10.4.4.4" = "subnet-d"
  }

I then have a terrafrom list object that looks like this

subnets_i_like = ["10.1.1.1","10.4.4.4"]

I want to iterate through this subnets_i_like list and filter out only the elements in the all_subnets map where the list element matches the map key … and create a new map, resulting in a new map that looks like this

new_map = {
    "10.1.1.1"  = "subnet-a"
    "10.4.4.4" = "subnet-d"
  }

Does anyone know how I would tackle this? I havent been able to find an example of this use case to guide me…Any help would be greatly appreciated

Hi @gbrt,

You can use the contains function to check if the a value is contained within the given list. For example:

> {for k, v in local.all_subnets : k => v if contains(local.subnets_i_like, k)}
{
  "10.1.1.1" = "subnet-a"
  "10.4.4.4" = "subnet-d"
}