Skipping resource creation, when resource consist for_each in code block

Hello, I’m new joiner in this community, before I never had a logical problems with HCL, however recently I faced an issue.

I have a resource which should be created only if parent resource is created, I know how to do it with count, but in my case, I have to use for_each

resource "aws_ec2_tag" "tgw_rtbl" {
   depends_on                      = [ aws_ec2_transit_gateway.tgw ] 
   resource_id                     = var.create_tgw_gateway ? aws_ec2_transit_gateway.tgw[0].association_default_route_table_id : ""
   key                             = each.key
   value                           = each.value
   
   lifecycle { 
       create_before_destroy       = true
       ignore_changes              = [ resource_id ] 
   }

   for_each  = { 
       "Name"  : local.tag_default_rtbl
       "Zone"  : upper(var.region)
       ... omitted ...
   }
}

FYI var.create_tgw_gateway = false

How can I implement a condition to skip creation of resource

P.S. Please do not judge my english very strong

Hi @unity-unity,

The rule for for_each is that your value must have at least one element per instance of the resource you want to create, and so to meet your requirement you need to ensure that for_each finds an empty map in the situation where no elements should be created.

Here is one way to write that:

  for_each = var.create_tgw_gateway ? tomap({
    Name = local.tag_default_rtbl
    Zone = upper(var.region)
  }) : tomap({})

I used the tomap function here to tell Terraform that the result of the conditional should be a map. That shouldn’t be necessary as long as all of your tag values have the same type, but giving Terraform that additional hint will allow it to give a better error message if a future change incorrectly includes a value that isn’t a string, because Terraform will have more information about what you intended the result to be.

1 Like

Wow, works perfectly as I expected, thank you so much for your help