Pass For_each GCP Service account email output to another Module to bind roles


I am trying to create google service account as well as binding roles to the given service account separately using modules.

I have 2 modules that I call. The first creates multiple service accounts (using for_each) and outputs the email of the service account.

I then want to pass that email output to another module and do a for_each to bind roles to given service account.

Please help me how can I fetch the generated mail id for each service account from the first module and how to pass to second module.

google_service_account module called
For_each used
Output service account email id’s (need help here)
google_project_iam_member module called
loop through service_accounts and fetch respective email id from module and do role binding

main_(service_accounts).txt (117 Bytes)
main_(sa_role_binding).txt (242 Bytes)

roles.json.txt (626 Bytes)
main.txt (1.2 KB)

The first thing you should change… is to stop using modules. Delete your entire modules/ directory, delete everything apart from the terraform and provider blocks from your top-level, and then add:

locals {
  json_data = jsondecode(file("./roles.json"))

resource "google_service_account" "service_accounts" {
  for_each   = toset(local.json_data.saroles[*].acct_id)
  account_id = each.key

resource "google_project_iam_member" "rolebinding" {
  for_each = merge([for v in local.json_data.saroles :
    { for role in v.roles :
      "${v.acct_id} ${role}" => merge({ role = role }, v)
  project = each.value.project_id
  role    = each.value.role
  member  = "serviceAccount:${google_service_account.service_accounts[each.value.acct_id].email}"

Modules exist to enable re-use of significant chunks of code. If you find yourself trying to put every resource in its own module, even when there are close relationships between different resources, as you have here, you’ve fallen into a trap of using the incorrect tool for the task.

Thank you for quick response max.
I totally agree with you on using resources, however I have to strictly follow to use modules developed by our organization. We are using terraform cloud and every employee should use existing modules.

So please suggest me is there any possibility to pass one module for-each output values as parameters to another module.

Thank you,

Hi Team can anyone help me here regarding above question.