I want to create a service account on GCP using a python script calling the REST API and then give it specific roles - ideally some of these, such as roles/logging.logWriter
.
First I make a request to create the account which works fine and I can see the account in Console/IAM.
Second I want to give it the role and this seems like the right method. However, it is not accepting roles/logging.logWriter
, saying HttpError 400, "Role roles/logging.logWriter is not supported for this resource.">
Conversely, if I set the desired policy in console, then try the getIamPolicy
method (using the gcloud tool), all I get back is response etag: ACAB
, no mention of the actual role I set. Hence I think these roles refer to different things.
Any idea how to go about scripting a role/scope for a service account using the API?
Under "Service Accounts" click the checkbox next to the service account email address. A panel will open. This is the right-side panel in your screenshot. However, in your case, you are using the service account as an identity , so you need to add the roles to the project under the "IAM" section.
serviceAccountUser ) at the project level for all service accounts in the project, or at the service account level. Granting the Service Account User role to a user for a project gives the user access to all service accounts in the project, including service accounts that might be created in the future.
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:
GCP_SVC_ACC
is expected to contain the email notation for the service account.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With