multiple --role for `gcloud iam service-accounts add-iam-policy-binding`

To add multiple IAM policies via gcloud, one must run multiple commands. For example:

```
gcloud iam service-accounts add-iam-policy-binding [SERVICE_ACCOUNT_EMAIL] \
--member='[MEMBER]' \
--role='[ROLE_1]'

gcloud iam service-accounts add-iam-policy-binding [SERVICE_ACCOUNT_EMAIL] \
--member='[MEMBER]' \
--role='[ROLE_2]'
```

It would be much more efficient to allow for multiple `--role` parameters (or multiple values for `--role`).,

For example:

```
gcloud iam service-accounts add-iam-policy-binding [SERVICE_ACCOUNT_EMAIL] \
--member='[MEMBER]' \
--role='[ROLE_1]' \
--role='[ROLE_2]'
```

Or multiple values for the cli flag:

```
gcloud iam service-accounts add-iam-policy-binding [SERVICE_ACCOUNT_EMAIL] \
--member='[MEMBER]' \
--role='[ROLE_1]' '[ROLE_2]'
```

2 4 875
4 REPLIES 4

Greetings @nick-youngblut,

Thank you for your suggestion. You can file this as a feature request in Google Cloud's Issue Tracker

As a workaround, you can create a script instead. You can use the following code below (I have tested this and it worked):

1. Create the script - $ nano roles.sh

 

#!/bin/bash

# Define the service account email, change the xxxxx
SERVICE_ACCOUNT_EMAIL="xxxxx"

# Define the roles that you want in an array
roles=(
    "roles/editor"
    "roles/iam.serviceAccountUser"
)

# Loop through each role and assign it to the service account
for role in "${roles[@]}"; do
    gcloud iam service-accounts add-iam-policy-binding $SERVICE_ACCOUNT_EMAIL \
        --role="$role" \
        --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL"
done

 

2. Add permission to the script file - $ chmod +x roles.sh

3. Execute the script - $ ./roles.sh

Please let me know if that was helpful. Thank you! 😃

While a script can work, one must then write a script instead of a self-contained bash command. Also, one should check for errors in each iteration of the loop, which you do not include in your example; I'm guessing that many users would forget to include error checks, but such error checks can be built into `gcloud iam service-accounts add-iam-policy-binding` for multiple --role values.

chmod +x roles.sh

MSH
Bronze 1
Bronze 1

The executable can prompt you for things like dynamic conditions which throws a wrench in the scripting department.