Manage access to service accounts Stay organized with collections Save and categorize content based on your preferences.
This page describes how to grant, change, and revoke a principal's access to asingle service account. To manage a principal's access to all service accountsin a project, folder, or organization, manage their access at theproject,folder, or organization level.
Note: You can get AI-powered help from the IAM role picker (Preview) to find and grant the right predefined roles to your principals. For more information, seeGet predefined role suggestions with Gemini assistance.In Identity and Access Management (IAM), access is managed throughallow policies, alsoknown as IAM policies. An allow policy is attached to aGoogle Cloud resource. Each allow policy contains a collection ofrolebindings that associate one or more principals, such as users or serviceaccounts, with an IAM role. These role bindings grant thespecified roles to the principals, both on the resource that the allow policy isattached to and on all of that resource'sdescendants. Formore information about allow policies, seeUnderstanding allow policies.
Service accounts are both resources that other principals can be granted accessto, and principals that can be granted access to other resources. This pagetreats service accounts as resources and describes how to grant other principalsaccess to them. To learn how to grant a service account access to otherresources, the following guides:
- To grant a service account access to a project, folder, or organization, seeManaging access to projects, folders, and organizations.
- To grant a service account access to other resources, seeManaging access to other resources.
This page describes how to manage access to service accounts using theGoogle Cloud console, the Google Cloud CLI, and the REST API. You can also manageaccess using theIAM client libraries.
Note: You can also use deny policies to prevent principals from using specific IAM permissions. For more information, seeDeny policies.
Before you begin
- Learn aboutservice accounts.
- Ensure that you have therequired IAMroles.
Required roles
To get the permissions that you need to manage access to a service account, ask your administrator to grant you theService Account Admin (roles/iam.serviceAccountAdmin) IAM role on the service account or the project that owns the serviceaccount. For more information about granting roles, seeManage access to projects, folders, and organizations.
This predefined role contains the permissions required to manage access to a service account. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to manage access to a service account:
iam.serviceAccounts.getiam.serviceAccounts.listiam.serviceAccounts.getIamPolicyiam.serviceAccounts.setIamPolicy
You might also be able to get these permissions withcustom roles or otherpredefined roles.
View current access
The following section shows you how to use the Google Cloud console, thegcloud CLI, and the REST API to view who has access to a serviceaccount. You can also view access by using theIAM clientlibraries to get the service account's allow policy.
Console
Note: The Google Cloud console shows access in a list form, rather thandirectly showing the resource's allow policy.In the Google Cloud console, go to theService Accounts page.
Select a project.
Click the email address of the service account.
Go to thePrincipals with access tab. The table lists all the principalswho have been granted a role on the service account.
This list includes principals whose access comes from roles that are grantedon parent resources. For more information about policy inheritance, seePolicy inheritance and the resource hierarchy.
Optional: To view role grants forservice agents, selecttheInclude Google-provided role grants checkbox.
gcloud
To see who has access to your service account, get the allow policy for theservice account. To learn how to interpret allow policies, seeUnderstanding allow policies.
Note: A resource's allow policy does not show any roles gained throughpolicy inheritance. To view inherited roles, use the Google Cloud console, or follow the instructions onViewing effective IAM policies.
To get the allow policy for the service account, run theget-iam-policy command for the service account:
gcloudiamservice-accountsget-iam-policySA_ID--format=FORMAT>PATHProvide the following values:
SA_ID: The ID of your service account. This caneither be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com,or the service account's unique numeric ID.FORMAT: The format for the policy. Usejsonoryaml.PATH: The path to a new output file for the policy.
For example, the following command gets the policy for the service accountmy-service-account and saves it to your home directory in JSON format:
gcloudiamservice-accountsget-iam-policymy-service-account--formatjson>~/policy.json
REST
To see who has access to your service account, get the allow policy for theservice account. To learn how to interpret allow policies, seeUnderstanding allow policies.
Note: A resource's allow policy does not show any roles gained throughpolicy inheritance. To view inherited roles, use the Google Cloud console, or follow the instructions onViewing effective IAM policies.
TheserviceAccounts.getIamPolicy method gets a service account's allow policy.
Before using any of the request data, make the following replacements:
PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
Note: To identify a service account just after it is created, use its numeric ID rather than its email address.SA_ID: The ID of your service account.This can either be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com, or the serviceaccount's unique numeric ID.POLICY_VERSION: The policy version to bereturned. Requests should specify the most recent policy version, which is policy version3. SeeSpecifyinga policy version when getting a policy for details.
HTTP method and URL:
POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:getIamPolicy
Request JSON body:
{ "options": { "requestedPolicyVersion":POLICY_VERSION }}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:getIamPolicy"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:getIamPolicy" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
The response contains the service account's allow policy. For example:
{ "version": 1, "etag": "BwWKmjvelug=", "bindings": [ { "role": "roles/serviceAccountAdmin", "members": [ "user:my-user@example.com" ] } ]}Grant or revoke a single IAM role
You can use the Google Cloud console and the gcloud CLI to quicklygrant or revoke a single role for a single principal, without editing theservice account's allow policy directly.Common types of principals include GoogleAccounts, service accounts, Google groups, and domains.For a list of allprincipal types, seePrincipal types. Note: If theiam.allowedPolicyMemberDomains organization policy constraint is enforced in your organization, then you might not be able to grant roles to newly created groups. If you get afailedPrecondition error when trying to grant a role to a newly created group, wait 24 hours, and then try granting the role again.
In general, policy changes take effect within 2 minutes. However, in some cases, itcan take 7 minutes or more for changes to propagate across the system.
If you need help identifying the most appropriate predefined role, seeFind the right predefined roles.
Grant a single IAM role
To grant a single role to a principal, do the following:
Console
In the Google Cloud console, go to theService Accounts page.
Select a project.
Click the email address of the service account.
Go to thePermissions tab and find the sectionPrincipals with accessto this service account.
Select a principal to grant a role to:
To grant a role to a principal who already has other roles on the serviceaccount, find a row containing the principal, then clickEditprincipal in that row, then clickAdd anotherrole.
To grant a role to aservice agent, select theIncludeGoogle-provided role grants checkbox to see its email address.
Note: You cannot edit inherited roles when managing access to serviceaccounts. To edit inherited roles, go to the resource where therole was granted.To grant a role to a principal who doesn't have any existing roles on theservice account, click
person_addGrant access, then enter anidentifier for the principal—for example, my-user@example.comor//iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.
Select a role to grant from the drop-down list. For best security practices,choose a role that includes only the permissions that your principal needs.
Optional: Add acondition to the role.
ClickSave. The principal is granted the role on the service account.
gcloud
To quickly grant a role to a principal, run theadd-iam-policy-binding command:
gcloudiamservice-accountsadd-iam-policy-bindingSA_ID\--member=PRINCIPAL--role=ROLE_NAME\--condition=CONDITION
Provide the following values:
SA_ID: The ID of your service account. This caneither be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com,or the service account's unique numeric ID.PRINCIPAL: An identifier for the principal, or member,which usually has the following form:PRINCIPAL-TYPE:ID.For example,user:my-user@example.comorprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.For a full list of the values thatPRINCIPALcan have,seePrincipal identifiers.For the principal type
user, the domain name in the identifier must bea Google Workspace domain or a Cloud Identity domain. To learn how to setup a Cloud Identity domain, see theoverview of Cloud Identity.ROLE_NAME: The name of the role that you want togrant. Use one of the following formats:- Predefined roles:
roles/SERVICE.IDENTIFIER - Project-level custom roles:
projects/PROJECT_ID/roles/IDENTIFIER - Organization-level custom roles:
organizations/ORG_ID/roles/IDENTIFIER
For a list of predefined roles, seeUnderstandingroles.
- Predefined roles:
CONDITION: Optional. The condition to add to the rolebinding. For more information about conditions, see theconditions overview.
For example, to grant the Service Account User role to the usermy-user@example.comfor the service accountmy-service-account@my-project.iam.gserviceaccount.com:
gcloudiamservice-accountsadd-iam-policy-bindingmy-service-account@my-project.iam.gserviceaccount.com\--member=user:my-user@example.com--role=roles/iam.serviceAccountUser
Revoke a single IAM role
To revoke a single role from a principal, do the following:
Console
In the Google Cloud console, go to theService Accounts page.
Select a project.
Click the email address of the service account.
Go to thePermissions tab and find the sectionPrincipals with accessto this service account.
Find the row containing the principal whose access you want to revoke. Then,clickEditprincipal in that row.
Note: You cannot edit inherited roles when managing access to serviceaccounts. To edit inherited roles, go to the resource where therole was granted.Click theDelete button forthe role that you want to revoke, and then clickSave.
gcloud
To quickly revoke a role from a user, run theremove-iam-policy-binding command:
gcloudiamservice-accountsremove-iam-policy-bindingSA_ID\--member=PRINCIPAL--role=ROLE_NAME
Provide the following values:
SA_ID: The ID of your service account. This caneither be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com,or the service account's unique numeric ID.PRINCIPAL: An identifier for the principal, or member,which usually has the following form:PRINCIPAL-TYPE:ID.For example,user:my-user@example.comorprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.For a full list of the values thatPRINCIPALcan have,seePrincipal identifiers.For the principal type
user, the domain name in the identifier must bea Google Workspace domain or a Cloud Identity domain. To learn how to setup a Cloud Identity domain, see theoverview of Cloud Identity.ROLE_NAME: The name of the role that you want torevoke. Use one of the following formats:- Predefined roles:
roles/SERVICE.IDENTIFIER - Project-level custom roles:
projects/PROJECT_ID/roles/IDENTIFIER - Organization-level custom roles:
organizations/ORG_ID/roles/IDENTIFIER
For a list of predefined roles, seeUnderstandingroles.
- Predefined roles:
For example, to revoke the Service Account User role from the usermy-user@example.comfor the service accountmy-service-account@my-project.iam.gserviceaccount.com:
gcloudiamservice-accountsremove-iam-policy-bindingmy-service-account@my-project.iam.gserviceaccount.com\--member=user:my-user@example.com--role=roles/iam.serviceAccountUser
Grant or revoke multiple IAM roles using the Google Cloud console
You can use the Google Cloud console to grant and revoke multiple roles fora single principal:
In the Google Cloud console, go to theService Accounts page.
Select a project.
Click the email address of the service account.
Go to thePermissions tab and find the sectionPrincipals with accessto this service account.
Select the principal whose roles you want to modify:
To modify roles for a principal who already has roles on the serviceaccount, find a row containing the principal, then clickEditprincipal in that row, then clickAdd anotherrole.
To modify roles for aservice agent, select theInclude Google-provided role grants checkbox to see itsemail address.
Note: You cannot edit inherited roles when managing access to serviceaccounts. To edit inherited roles, go to the resource where therole was granted.To grant roles to a principal who doesn't have any existing roles on theservice account, click
person_addGrant access, then enter theprincipal's email address or other identifier.
Modify the principal's roles:
- To grant a role to a principal who doesn't have any existing roles on theresource, clickSelect a role, then select a role to grant from thedrop-down list.
- To grant an additional role to the principal, clickAdd another role,then select a role to grant from the drop-down list.
- To replace one of the principal's roles with a different role, click theexisting role, then choose a different role to grant from the drop-downlist.
- To revoke one of the principal's roles, click theDelete
You can alsoadd a condition to a role,modify a role'scondition, orremove a role'scondition.
ClickSave.
Grant or revoke multiple IAM roles programmatically
To make large-scale access changes that involve granting and revoking multipleroles for multiple principals, use theread-modify-write pattern to update theservice account's allow policy:
- Read the current allow policy by calling
getIamPolicy(). - Edit the allow policy, either by using a text editor or programmatically, toadd or remove any principals or role bindings.
- Write the updated allow policy by calling
setIamPolicy().
This section shows how to use the gcloud CLI and the REST API toupdate the allow policy. You can also update the allow policy using theIAM client libraries.
Note: If theiam.allowedPolicyMemberDomains organization policy constraint is enforced in your organization, then you might not be able to grant roles to newly created groups. If you get afailedPrecondition error when trying to grant a role to a newly created group, wait 24 hours, and then try granting the role again.
In general, policy changes take effect within 2 minutes. However, in some cases, itcan take 7 minutes or more for changes to propagate across the system.
Get the current allow policy
gcloud
To get the allow policy for the service account, run theget-iam-policy command for the service account:
gcloudiamservice-accountsget-iam-policySA_ID--format=FORMAT>PATHProvide the following values:
SA_ID: The ID of your service account. This caneither be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com,or the service account's unique numeric ID.FORMAT: The format for the allow policy. Usejsonoryaml.PATH: The path to a new output file for the allowpolicy.
For example, the following command gets the allow policy for the service accountmy-service-account and saves it to your home directory in JSON format:
gcloudiamservice-accountsget-iam-policymy-service-account--formatjson>~/policy.json
REST
TheserviceAccounts.getIamPolicy method gets a service account's allow policy.
Before using any of the request data, make the following replacements:
PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
Note: To identify a service account just after it is created, use its numeric ID rather than its email address.SA_ID: The ID of your service account.This can either be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com, or the serviceaccount's unique numeric ID.POLICY_VERSION: The policy version to bereturned. Requests should specify the most recent policy version, which is policy version3. SeeSpecifyinga policy version when getting a policy for details.
HTTP method and URL:
POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:getIamPolicy
Request JSON body:
{ "options": { "requestedPolicyVersion":POLICY_VERSION }}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:getIamPolicy"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:getIamPolicy" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
The response contains the service account's allow policy. For example:
{ "version": 1, "etag": "BwWKmjvelug=", "bindings": [ { "role": "roles/serviceAccountAdmin", "members": [ "user:my-user@example.com" ] } ]}Save the response in a file of the appropriate type (json oryaml).
Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.ServiceAccountName;importcom.google.iam.v1.GetIamPolicyRequest;importcom.google.iam.v1.Policy;importjava.io.IOException;publicclassGetServiceAccountPolicy{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your project ID.StringprojectId="your-project-id";// TODO: Replace with your service account name.StringserviceAccount="your-service-account";getPolicy(projectId,serviceAccount);}// Gets a service account's IAM policy.publicstaticPolicygetPolicy(StringprojectId,StringserviceAccount)throwsIOException{// Construct the service account email.// You can modify the ".iam.gserviceaccount.com" to match the name of the service account// whose allow policy you want to get.StringserviceAccountEmail=serviceAccount+"@"+projectId+".iam.gserviceaccount.com";// Initialize client that will be used to send requests.// This client only needs to be created once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){GetIamPolicyRequestrequest=GetIamPolicyRequest.newBuilder().setResource(ServiceAccountName.of(projectId,serviceAccountEmail).toString()).build();Policypolicy=iamClient.getIamPolicy(request);System.out.println("Policy retrieved: "+policy.toString());returnpolicy;}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
fromgoogle.cloudimportiam_admin_v1fromgoogle.iam.v1importiam_policy_pb2,policy_pb2defget_service_account_iam_policy(project_id:str,account:str)->policy_pb2.Policy:"""Get policy for service account. project_id: ID or number of the Google Cloud project you want to use. account: ID or email which is unique identifier of the service account. """iam_client=iam_admin_v1.IAMClient()request=iam_policy_pb2.GetIamPolicyRequest()request.resource=f"projects/{project_id}/serviceAccounts/{account}"policy=iam_client.get_iam_policy(request)returnpolicyModify the allow policy
Programmatically or using a text editor, modify the local copy of your serviceaccount's allow policy to reflect the roles you want to grant or revoke to givenusers.
To ensure that you don't overwrite other changes, don't edit or remove theallow policy'setag field. Theetag field identifies the current state ofthe allow policy. When youset the updated allow policy,IAM compares theetag value in the request with theexistingetag, and only writes the allow policy if the values match.
To edit the roles that an allow policy grants, you need to edit the rolebindings in the allow policy. Role bindings have the following format:
{"role":"ROLE_NAME","members":["PRINCIPAL_1","PRINCIPAL_2",..."PRINCIPAL_N"],"conditions:"{CONDITIONS}}
The placeholders have the following values:
ROLE_NAME: The name of the role that you want togrant. Use one of the following formats:- Predefined roles:
roles/SERVICE.IDENTIFIER - Project-level custom roles:
projects/PROJECT_ID/roles/IDENTIFIER - Organization-level custom roles:
organizations/ORG_ID/roles/IDENTIFIER
For a list of predefined roles, seeUnderstandingroles.
- Predefined roles:
PRINCIPAL_1,PRINCIPAL_2,...PRINCIPAL_N: Identifiers for the principals thatyou want to grant the role to.Principal identifiers usually have the following form:
PRINCIPAL-TYPE:ID.For example,user:my-user@example.comorprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.For a full list of the values thatPRINCIPALcan have,seePrincipal identifiers.For the principal type
user, the domain name in the identifier must bea Google Workspace domain or a Cloud Identity domain. To learn how to setup a Cloud Identity domain, see theoverview of Cloud Identity.CONDITIONS: Optional. Anyconditionsthat specify when access will be granted.
Grant a role
To grant roles to your principals, modify the role bindings in the allow policy.To learn what roles you can grant, seeUnderstanding roles, orview grantable roles for the service account. If you needhelp identifying the most appropriate predefined roles, seeFind the right predefined roles.
Optionally, you can useconditions to grant roles only whencertain requirements are met.
To grant a role that is already included in the allow policy, add the principalto an existing role binding:
gcloud
Edit the allow policy by adding the principal to an existing role binding. Notethat this change will not take effect until youset the updated allow policy.
For example, imagine the allow policy contains the following role binding, whichgrants the Service Account User role (roles/iam.serviceAccountUser) toKai:
{"role":"roles/iam.serviceAccountUser","members":["user:kai@example.com"]}To grant that same role to Raha, add Raha to theexisting role binding:
{"role":"roles/iam.serviceAccountUser","members":["user:kai@example.com","user:raha@example.com"]}
REST
Edit the allow policy by adding the principal to an existing role binding. Notethat this change will not take effect until youset the updated allow policy.
For example, imagine the allow policy contains the following role binding, whichgrants the Service Account User role (roles/iam.serviceAccountUser) toKai:
{"role":"roles/iam.serviceAccountUser","members":["user:kai@example.com"]}To grant that same role to Raha, add Raha to theexisting role binding:
{"role":"roles/iam.serviceAccountUser","members":["user:kai@example.com","user:raha@example.com"]}
To grant a role that is not yet included in the allow policy, add a new rolebinding:
gcloud
Edit the allow policy by adding a new role binding that grants the role to theprincipal. This change will not take effect until youset the updated allow policy.
For example, to grant the Service Account Token Creator role(roles/iam.serviceAccountTokenCreator) to Raha, add thefollowing role binding to thebindings array for the allow policy:
{"role":"roles/iam.serviceAccountTokenCreator","members":["user:raha@example.com"]}REST
Edit the allow policy by adding a new role binding that grants the role to theprincipal. This change will not take effect until youset the updated allow policy.
For example, to grant the Service Account Token Creator role(roles/iam.serviceAccountTokenCreator) to Raha, add thefollowing role binding to thebindings array for the allow policy:
{"role":"roles/iam.serviceAccountTokenCreator","members":["user:raha@example.com"]}Revoke a role
To revoke a role, remove the principal from the role binding. If there are noother principals in the role binding, remove the entire role binding from theallow policy.
Note: Role bindings with no principals are not allowed and will result in anerror when setting the allow policy.gcloud
Edit the allow policy by removing the principal or the entire role binding. Thischange will not take effect until youset the updated allow policy.
For example, imagine the allow policy contains the following role binding, whichgrants Kai and Raha the Service Account User role(roles/iam.serviceAccountUser):
{"role":"roles/iam.serviceAccountUser","members":["user:kai@example.com","user:raha@example.com"]}To revoke the role from Kai, remove Kai's principal identifier from therole binding:
{"role":"roles/iam.serviceAccountUser","members":[user:raha@example.com]}To revoke the role from both Kai and Raha, remove the role binding from theallow policy.
REST
Edit the allow policy by removing the principal or the entire role binding. Thischange will not take effect until youset the updated allow policy.
For example, imagine the allow policy contains the following role binding, whichgrants Kai and Raha the Service Account User role(roles/iam.serviceAccountUser):
{"role":"roles/iam.serviceAccountUser","members":["user:kai@example.com","user:raha@example.com"]}To revoke the role from Kai, remove Kai's principal identifier from therole binding:
{"role":"roles/iam.serviceAccountUser","members":[user:raha@example.com]}To revoke the role from both Kai and Raha, remove the role binding from theallow policy.
Set the allow policy
After you modify the allow policy to grant and revoke roles, callsetIamPolicy() to make the updates.
gcloud
To set the allow policy for the resource, run theset-iam-policy command for the service account:
gcloudiamservice-accountsset-iam-policySA_IDPATH
Provide the following values:
SA_ID: The ID of your service account. This caneither be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com,or the service account's unique numeric ID.PATH: The path to a file that contains the newallow policy.
The response contains the updated allow policy.
For example, the following command sets the allow policy stored inpolicy.jsonas the allow policy for the service accountmy-service-account@my-project.iam.gserviceaccount.com:
gcloudiamservice-accountsset-iam-policymy-service-account@my-project.iam.gserviceaccount.com\~/policy.jsonREST
TheserviceAccounts.setIamPolicy method sets an updated allow policy for the service account.
Before using any of the request data, make the following replacements:
PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
Note: To identify a service account just after it is created, use its numeric ID rather than its email address.SA_ID: The ID of your service account.This can either be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com, or the serviceaccount's unique numeric ID.POLICY: A JSON representation of the policy that youwant to set. For more information about the format of a policy, see thePolicy reference.For example, to set the allow policy shown in the previous step, replace
policywith the following:{"version":1,"etag":"BwUqLaVeua8=","bindings":[{"role":"roles/iam.serviceAccountUser","members":["group:my-group@example.com"]},{"role":"roles/serviceAccountAdmin","members":["user:my-user@example.com"]}]}
HTTP method and URL:
POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:setIamPolicy
Request JSON body:
{ "policy":POLICY}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:setIamPolicy"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID:setIamPolicy" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
The response contains the updated allow policy.
Note: If you treat policies as code and store them in a version-control system, you should store the policy that is returned, not the policy that you sent in the request.Java
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMJava API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.ServiceAccountName;importcom.google.iam.v1.Policy;importcom.google.iam.v1.SetIamPolicyRequest;importcom.google.protobuf.FieldMask;importjava.io.IOException;importjava.util.Arrays;importjava.util.List;publicclassSetServiceAccountPolicy{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.// TODO: Replace with your project ID.StringprojectId="your-project-id";// TODO: Replace with your service account name.StringserviceAccount="your-service-account";// TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).Policypolicy=Policy.newBuilder().build();setServiceAccountPolicy(policy,projectId,serviceAccount);}// Sets a service account's policy.publicstaticPolicysetServiceAccountPolicy(Policypolicy,StringprojectId,StringserviceAccount)throwsIOException{// Construct the service account email.// You can modify the ".iam.gserviceaccount.com" to match the name of the service account// whose allow policy you want to set.StringaccountEmail=String.format("%s@%s.iam.gserviceaccount.com",serviceAccount,projectId);// Initialize client that will be used to send requests.// This client only needs to be created once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){List<String>paths=Arrays.asList("bindings","etag");SetIamPolicyRequestrequest=SetIamPolicyRequest.newBuilder().setResource(ServiceAccountName.of(projectId,accountEmail).toString()).setPolicy(policy)// A FieldMask specifying which fields of the policy to modify. Only// the fields in the mask will be modified. If no mask is provided, the// following default mask is used:// `paths: "bindings, etag"`.setUpdateMask(FieldMask.newBuilder().addAllPaths(paths).build()).build();returniamClient.setIamPolicy(request);}}}Python
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMPython API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
fromgoogle.cloudimportiam_admin_v1fromgoogle.iam.v1importiam_policy_pb2,policy_pb2defset_service_account_iam_policy(project_id:str,account:str,policy:policy_pb2.Policy)->policy_pb2.Policy:"""Set policy for service account. Pay attention that previous state will be completely rewritten. If you want to update only part of the policy follow the approach read->modify->write. For more details about policies check out https://cloud.google.com/iam/docs/policies project_id: ID or number of the Google Cloud project you want to use. account: ID or email which is unique identifier of the service account. policy: Policy which has to be set. """# Same approach as for policies on project level,# but client stub is different.iam_client=iam_admin_v1.IAMClient()request=iam_policy_pb2.SetIamPolicyRequest()request.resource=f"projects/{project_id}/serviceAccounts/{account}"# request.etag field also will be merged which means# you are secured from collision, but it means that request# may fail and you need to leverage exponential retries approach# to be sure policy has been updated.request.policy.MergeFrom(policy)policy=iam_client.set_iam_policy(request)returnpolicyWhat's next
- Learn which roles to grant to allow principals toauthenticate as service accounts.
- Find out how tochoose the most appropriate predefined roles.
- ReviewBest practices for working with serviceaccounts to learn how to use service accountssecurely.
- Learn how tomanage access to projects, folders, andorganizations.
- Learn the general steps formanaging access to other resources.
- Learn how to make a principal's access conditional withconditional role bindings.
Try it for yourself
If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
Get started for freeExcept as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-18 UTC.