Adding roles to service accounts on Google Cloud Platform using REST API

You can grant permissions to a GCP service account in a GCP project without having to rewrite the entire project policy!

Use the gcloud projects add-iam-policy-binding ... command for that (docs).

For example, given the environment variables GCP_PROJECT_ID and GCP_SVC_ACC the following command grants all privileges in the container.admin role to the chosen service account:

gcloud projects add-iam-policy-binding ${GCP_PROJECT_ID} \
    --member=serviceAccount:${GCP_SVC_ACC}
    --role=roles/container.admin

To review what you've done:

$ gcloud projects get-iam-policy $GCP_PROJECT_ID \
    --flatten="bindings[].members" \
    --format='table(bindings.role)' \
    --filter="bindings.members:${GCP_SVC_ACC}"

Output:

ROLE
roles/container.admin

(or more roles, if those were granted before)

Notes:

  • The environment variable GCP_SVC_ACC is expected to contain the email notation for the service account.
  • Kudos to this answer for the nicely formatted readout.

You appear to be trying to set a role on the service account (as a resource). That's for setting who can use the service account.

If you want to give the service account (as an identity) a particular role on the project and its resources, see this method: https://cloud.google.com/resource-manager/reference/rest/v1/projects/setIamPolicy