for-loopterraformeachterraform-provider-aws

Module output to use as input in other module specifically with for_each


I need some guidance on below use case. I have one stack that has 30 aws target groups to create. So I am using a module with for_each with diff paramters and creating 30 Target groups. Now Later I need to create 30 listener forwarding rules where I have to pass output of above target group's arn. I am getting error that string required. I am sure output is a string and it works when I call module multiple time without for_each.

    module "listener_rule_Models" {
  source = "git::https://mycompany/_git/terraform-aws-alb-listener-rule"
    for_each = {
      "models" = {
        tg_arn = module.tgLOGIN["MODELS"].tg_arn
        forwarding_path = ["/my_service.application_path*"]
      },
      "indexEngine" = {
        tg_arn = module.tgLOGIN["MODELS"].tg_arn
        forwarding_path = ["/my_service2.application_path*"]
      }
    }
  listener_arn = module.lis-Consolidated81.listener_arn
  tg_arn       = each.value
  forwarding_path = [each.value]
}

Error : Invalid value for module argument

on main.tf line 181, in module "listener_rule_Models": 181: tg_arn = each.value

The given value is not suitable for child module variable "tg_arn" defined at .terraform\modules\listener_rule_Models\variables.tf:6,1-18: string required.

Error: Invalid value for module argument

on main.tf line 181, in module "listener_rule_Models": 181: tg_arn = each.value

The given value is not suitable for child module variable "tg_arn" defined at .terraform\modules\listener_rule_Models\variables.tf:6,1-18: string required.

Error: Invalid value for module argument

on main.tf line 182, in module "listener_rule_Models": 182: forwarding_path = [each.value]

The given value is not suitable for child module variable "forwarding_path" defined at .terraform\modules\listener_rule_Models\variables.tf:17,1-27: element 0: string required.

Error: Invalid value for module argument

on main.tf line 182, in module "listener_rule_Models": 182: forwarding_path = [each.value]


Solution

  • You missed referencing individual keys in the map instead you referenced map all together for both tg_arn & forwarding_path.

    module "listener_rule_Models" {
      source = "git::https://mycompany/_git/terraform-aws-alb-listener-rule"
      for_each = {
        "models" = {
          tg_arn          = module.tgLOGIN["MODELS"].tg_arn
          forwarding_path = ["/my_service.application_path*"]
        },
        "indexEngine" = {
          tg_arn          = module.tgLOGIN["MODELS"].tg_arn
          forwarding_path = ["/my_service2.application_path*"]
        }
      }
      listener_arn    = module.lis-Consolidated81.listener_arn
      tg_arn          = each.value.tg_arn
      forwarding_path = [each.value.forwarding_path]
    }