Create resource with for_each if specific attribute in map is set to true

Hi all,

I would like to have your advice please. Here is my problem :

locals {
  instances = {
    instance-1 = {
      create_eip = false
    },
    instance-2 = {
      create_eip = true
    }
  }
}

resource "aws_eip" "this" {
  for_each = element([for i in local.instances : lookup(i, "create_eip", false)], 0) ? local.instances : {}

  vpc      = true
  instance = aws_instance.this[each.key].id
}

I try to create and attach an EIP only if create_eip is set to true.

With the example above, obviously the element function takes the first (false) value only, so no EIP is created for instance-2.

Do you know how I could make this work ? Thanks a lot for your help.

Found out, it was quite simple in fact :

resource "aws_eip" "this" {
  for_each = {
    for k, v in local.instances :
    k => aws_instance.this[k].id
    if v.create_eip == true
  }

  vpc      = true
  instance = each.value
}