Search code examples
google-cloud-platformterraformterraform-provider-gcpgoogle-cloud-iam

How to resolve "googleapi: Error 403: The caller does not have permission, forbidden"


I am using terraform to build infra in GCP. I am trying to assign roles to a service account using terraform but unable to do so. Below is my code:

sa.tf:

resource "google_service_account" "mojo-terra" {
  account_id   = "mojo-terra"
  description  = "Service account used for terraform script"
}

resource "google_project_iam_member" "mojo-roles" {
  count = length(var.rolesList)
  role =  var.rolesList[count.index]
  member = "serviceAccount:${google_service_account.mojo-terra.email}"
}

dev.tfvars:

rolesList = [
    "roles/iam.serviceAccountUser"
]

cloudbuild logs:

Step #2: Error: Error when reading or editing Resource "project \"poc-dev\"" with IAM Policy: Error retrieving IAM policy for project "poc-dev": googleapi: Error 403: The caller does not have permission, forbidden
Step #2: 
Step #2: 
Step #2: 
Step #2: Error: Error when reading or editing Resource "project \"poc-dev\"" with IAM Member: Role "roles/iam.serviceAccountUser" Member "serviceAccount:asadsfs@poc-dev-1221.iam.gserviceaccount.com": Error retrieving IAM policy for project "poc-dev": googleapi: Error 403: The caller does not have permission, forbidden
Step #2: 

Below are the roles attached to my cloudbuild service account: Custom Role cloudbuild, Cloud Build Service Account, Service Account Admin, Create Service Accounts, Delete Service Accounts, Service Account User, Storage Admin


Solution

  • The service account providing authorization to Terraform is missing the permission resourcemanager.projects.getIamPolicy which is the source of the error message.

    The service account is also missing the permission resourcemanager.projects.setIamPolicy which is required to change IAM policies.

    Those permissions are part of the role roles/resourcemanager.projectIamAdmin (Project IAM Admin).

    To list the roles assigned to the service account:

    gcloud projects get-iam-policy <YOUR GCLOUD PROJECT ID> \
    --flatten="bindings[].members" \
    --format='table(bindings.role)' \
    --filter="bindings.members:<YOUR SERVICE ACCOUNT>"
    

    To list the permissions that a role contains:

    gcloud iam roles describe roles/resourcemanager.projectIamAdmin
    

    To add the required role to the service account:

    gcloud projects add-iam-policy-binding <YOUR GCLOUD PROJECT ID> \
    --member=serviceAccount:<YOUR SERVICE ACCOUNT> \
    --role=roles/resourcemanager.projectIamAdmin