For Each with conditions, and referencing

Hello, I’ve a resource kms I moved from count to for_each however I can not manage some moments:

toset function doesn’t working, the types should be identical, I don’t know how to convert

Could someone please assist on this

Here is the

resource "aws_kms_key"   "global"    {
   for_each                  = toset( var.create_keys ?  { for keys in var.parameters : => keys } : [] ) < Problem
   is_enabled                = var.create_keys
   policy                    = data.template_file.key_service.rendered
   key_usage                 = lookup(each.value, "usage",       "" )
   description               = lookup(each.value, "description", "" )
   enable_key_rotation       = lookup(each.value, "rotation", false )
   deletion_window_in_days   = lookup(each.value, "lifetime",    "" )
   customer_master_key_spec  = lookup(each.value, "customer",    "" )

   lifecycle { 
       create_before_destroy  = false
       ignore_changes         = [ policy ]

   tags = var.tags

Variables as well

variable "parameters"                {
   description = "The parameters of key(s)"
   type        = list(map(string))
   default     = null

variable "create_keys"               {
   description = "Condition to create key"
   type        = bool
   default     = true

I’m wondering if a simple if could do it.

for_each = { for keys in var.parameters : => keys  if var.create_keys == true }
1 Like

@tbugfinder, You’re my saviour, thank you so much, I really really appreciated again your help.
I’m sorry, but is it possible to ask one more question, if you don’t mind? Or it is better to create another topic?

well, if it’s different then a new topic might make sense.

1 Like

@tbugfinder, Actually is not a different, I’ve moved also my vpc from count to for_each with you help. But now I can not grep the main_route_table_id to tag it with aws_ec2_tag resource.

Hm, would need a code snippet.

1 Like

Hello, @tbugfinder Sorry for late response, let me show you

resource "aws_ec2_tag" "local_route_table"         {
   for_each                  = local.tags
   depends_on                = [ ]
   resource_id               =
   key                       = each.key
   value                     = each.value

   lifecycle {
       create_before_destroy = true
       ignore_changes        = [ resource_id ]

Before, I moved from count to for_each the resource_id were working with:[0].main_route_table_id

After when it starts to complain I tried with data source

data "aws_route_table" "selected" {
  route_table_id =[0].main_route_table_id

data "aws_route_table" "selected" {
  vpc_id =[0].id

Nothing is working, it says that my network is empty tuple

@tbugfinder I’ve found a solution, thank you again