Search code examples
google-cloud-platformgcloudgoogle-iamgoogle-cloud-iam

How to add a custom role to service account using gcloud


I created a service account: name@project.iam.gserviceaccount.com and a custom role mycustomrole.

How with gcloud command can I add the custom role to this service account?

When I try

gcloud projects add-iam-policy-binding my-project \
  --member="serviceAccount:myserviceaccount@myproject.iam.gserviceaccount.com" \
  --role=projects/myproject/roles/mycustomrole \
  --verbosity=debug

I get an error:

ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: The role name must be in the form "roles/{role}", "organizations/{organization_id}/roles/{role}", or "projects/{project_id}/roles/{role}".

I tried already:

  --role=roles/mycustomrole
  --role=projects/myproject/roles/mycustomrole
  --role=projects/myproject/roles/customrole/mycustomrole

Solution

  • With help from https://stackoverflow.com/users/609290/dazwilkin I was able to solve this.

    When creating a role in GCP, by default their ID is in format of CustomRoleXXXX, where XXXX is a random number.

    I was trying to use the name of the custom role instead of its ID.

    All commands:

    Create a custom role via UI.

    Check its ID in the UI or by running:

    gcloud iam roles list --project=<PROJECT ID> --format="value(name)"
    

    Attach a custom role to service account:

    gcloud projects add-iam-policy-binding <PROJECT ID> \
      --member="serviceAccount:myserviceaccount@myproject.iam.gserviceaccount.com" \
      --role=<CUSTOM ROLE ID> \
      --verbosity=debug