23w4ertfgyhj
23w4ertfgyhj

Reputation: 703

How to add a custom role to service account using gcloud

I created a service account: [email protected] 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:[email protected]" \
  --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

Upvotes: 2

Views: 2458

Answers (2)

23w4ertfgyhj
23w4ertfgyhj

Reputation: 703

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:[email protected]" \
  --role=<CUSTOM ROLE ID> \
  --verbosity=debug

Upvotes: 0

Mazlum Tosun
Mazlum Tosun

Reputation: 6572

I tried with the following command and it worked in my case :

gcloud projects add-iam-policy-binding my-project \
  --member="serviceAccount:[email protected]" \
  --role=projects/my-project/roles/my.role.name \
  --verbosity=debug

I was able to add the custom role projects/my-project/roles/my.role.name to the SA serviceAccount:[email protected].

For the custom role, you have to put the role ID, this ID is displayed in the role detail page :

enter image description here

If you tip the correct params and if it still results in an error, can you update your gcloud version and try again please ?

gcloud components update

Upvotes: 4

Related Questions