Search code examples
google-cloud-platformgcloudrolesgoogle-cloud-iam

Issues Assigning Roles to a Service Account in Google Cloud


I'm trying to assign roles to a service account in Google Cloud via the gcloud command line. I created the service account using the following command:

gcloud iam service-accounts create ai-ga-service-account --description="Service account for GitHub Actions" --display-name="ai-ga-service-account"

I attempted to assign the "Artifact Registry Writer" and "Kubernetes Engine Developer" roles to the service account using these commands:

gcloud projects add-iam-policy-binding ${PROJECT_ID} --member="serviceAccount:ai-ga-service-account@${PROJECT_ID}.iam.gserviceaccount.com" --role="roles/artifactregistry.writer"
gcloud projects add-iam-policy-binding ${PROJECT_ID} --member="serviceAccount:ai-ga-service-account@${PROJECT_ID}.iam.gserviceaccount.com" --role="roles/container.developer"

However, when I try to verify the roles assigned to the service account with this command:

gcloud iam service-accounts get-iam-policy ai-ga-service-account@${PROJECT_ID}.iam.gserviceaccount.com --format json

I get the following output:

{
  "etag": "ACAB"
}

This seems to indicate that no roles were assigned to the service account. Could anyone help me understand what's going on and how I can properly assign these roles to the service account?

Thank you in advance.


Solution

  • You are adding IAM policy bindings to the project for the service account principal. Then you are trying to read the IAM policy bindings for the service account. Those are different resources (project versus service-account).

    Use this command:

    gcloud projects get-iam-policy $PROJECT_ID
    

    Note: service accounts do support IAM policy bindings. That is used to specify who is allowed to use the service account as a resource (impersonation, creating tokens, etc.). In your case you are adding IAM policy bindings for the service account's identity (email address) to grant permissions to the service account.