Manage access to service accounts

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:

Note: Granting roles on service accounts can allow principals to impersonateservice accounts. SeeRoles for service account authentication for more information.

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

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.get
  • iam.serviceAccounts.list
  • iam.serviceAccounts.getIamPolicy
  • iam.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.

Note: If you grant access to a user's email alias or a secondary domain, then the values in your allow policy might not match the values that you initially entered. If you grant access to an email alias, then the allow policy displays the user's primary email address. If you grant access to a secondary domain, then the allow policy displays the primary domain.

Console

Note: The Google Cloud console shows access in a list form, rather thandirectly showing the resource's allow policy.
  1. In the Google Cloud console, go to theService Accounts page.

    Go to Service Accounts

  2. Select a project.

  3. Click the email address of the service account.

  4. 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.

  5. 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>PATH

Provide the following values:

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:

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

  1. In the Google Cloud console, go to theService Accounts page.

    Go to Service Accounts

  2. Select a project.

  3. Click the email address of the service account.

  4. Go to thePermissions tab and find the sectionPrincipals with accessto this service account.

  5. Select a principal to grant a role to:

  6. 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.

  7. Optional: Add acondition to the role.

  8. 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:

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

Note: If you grant access to a user's email alias or a secondary domain, then the values in your allow policy might not match the values that you initially entered. If you grant access to an email alias, then the allow policy displays the user's primary email address. If you grant access to a secondary domain, then the allow policy displays the primary domain.

Revoke a single IAM role

To revoke a single role from a principal, do the following:

Console

  1. In the Google Cloud console, go to theService Accounts page.

    Go to Service Accounts

  2. Select a project.

  3. Click the email address of the service account.

  4. Go to thePermissions tab and find the sectionPrincipals with accessto this service account.

  5. 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.
  6. 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:

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:

  1. In the Google Cloud console, go to theService Accounts page.

    Go to Service Accounts

  2. Select a project.

  3. Click the email address of the service account.

  4. Go to thePermissions tab and find the sectionPrincipals with accessto this service account.

  5. Select the principal whose roles you want to modify:

  6. Modify the principal's roles:

    You can alsoadd a condition to a role,modify a role'scondition, orremove a role'scondition.

  7. ClickSave.

Note: If you grant access to a user's email alias or a secondary domain, then the values in your allow policy might not match the values that you initially entered. If you grant access to an email alias, then the allow policy displays the user's primary email address. If you grant access to a secondary domain, then the allow policy displays the primary domain.

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:

  1. Read the current allow policy by callinggetIamPolicy().
  2. Edit the allow policy, either by using a text editor or programmatically, toadd or remove any principals or role bindings.
  3. Write the updated allow policy by callingsetIamPolicy().

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>PATH

Provide the following values:

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:

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)returnpolicy

Modify 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.

Important: None of your changes to the allow policy will take effect until youset the updated allow policy.

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.

  • 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.com orprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com.For a full list of the values thatPRINCIPAL can have,seePrincipal identifiers.

    For the principal typeuser, 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.

Warning: Setting a new allow policy permanently overwrites the existing allowpolicy on the service account. To avoid removing role bindings unintentionally,always follow the read-modify-write pattern when updating an allow policy: readthe existing policy, modify it as needed, and then write the updated version ofthe allow policy.

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:

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.json

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.

REST

TheserviceAccounts.setIamPolicy method sets an updated allow policy for the service account.

Before using any of the request data, make the following replacements:

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)returnpolicy

Note: If you grant access to a user's email alias or a secondary domain, then the values in your allow policy might not match the values that you initially entered. If you grant access to an email alias, then the allow policy displays the user's primary email address. If you grant access to a secondary domain, then the allow policy displays the primary domain.

What's next

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 free

Except 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.