For_each module output

I am trying to loop over the output from some modules but can’t get the key used to create the child module

eg i create multiple modules using a list

module "services" {
  for_each = var.clients
  source = "./service"
...some variables
}

resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = aws_s3_bucket.ftp.id
  dynamic "lambda_function" {
    for_each = [for s in module.services: {
      name   = s.**id**
      lambda_arn = s.lambda_arn
    }]
    content {
      id="updates_${lambda_function.key}"
      lambda_function_arn = lambda_function.value.lambda_arn
      events = ["s3:ObjectCreated:*"]
      filter_prefix = "${lambda_function.value.name}/"
    }
  }
}

I can get the out declared in module but can’t access the ‘index’ which was used to create the modules. I have tried id, name, index but can’t access it. Is there a way to get the index?

thanks
Andy

Hi @acraftydev,

When you say “the key used to create the child module”, are you referring to the value that each.key would have if you used it in the module "services" block?

If so, you can make use of the fact that module.services is a map whose keys are the same as in the var.clients map, using the two-variable version of for expression to get both the key and the value:

    for_each = [for k, s in module.services : {
      name       = k
      lambda_arn = s.lambda_arn
    }]
1 Like

yes my mistake i wasn’t looping over the key/values from the map
"for s in module.services " -> "for k,s in module.services "