gcp, terraform,

google_project_iam_binding removes GCP compute engine default service accounts from IAM principals

Jul 13, 2022 · 1 min read · 5 views · Post a comment

By default, once you enable the Compute Engine API in GCP, two Google-managed service account principals will be created Compute Engine default service account and Google APIs service account. Both assigned with the Editor role.

The gotcha moment comes if you are using the google_project_iam_binding Terraform resource, these SAs will be planned to be destroyed on the next terraform apply.

How come?! Simply put, google_project_iam_binding resource is authoritative meaning it will delete anything that’s not part of the tfstate hence including the above-mentioned.

Prerequisites

  • GCP account
  • Terraform

Solution

Step 1. Replace google_project_iam_binding with the non-authoritative google_project_iam_member. So, instead of:

resource "google_project_iam_binding" "project_editor" {
  project = local.project_id
  role    = "roles/editor"

  members = [
    "serviceAccount:${module.init_projects.project_sa_email}",
  ]
}

you’ll have something like this:

resource "google_project_iam_member" "project_editor" {
  project = local.project_id
  role    = "roles/editor"
  member  = "serviceAccount:${module.init_projects.project_sa_email}"
}

Step 2. Given the SAs are already gone, under IAM & Admin, click ADD.
gcp iam add

Step 3. Assign both principals the Editor role and click SAVE.
gcp iam add principals editor

Conclusion

Related GitHub issue: Terraform google_project_iam_binding deletes GCP compute engine default service account from IAM principals. Tried everything and nothing works? Let me know. On a side note, follow our official channel on Telegram.