Attach service accounts to resources Stay organized with collections Save and categorize content based on your preferences.
For some Google Cloud resources, you can specify a user-managed service account that theresource uses as its default identity. This process is known asattaching the serviceaccount to the resource, orassociating the service account with the resource.When code running on the resource accesses Google Cloud services and resources, it uses theservice account attached to the resource as its identity. For example, if youattach aservice account to a Compute Engine instance, and the applications on the instance use aclient library to call Google Cloud APIs,those applications automatically use the attached service account for authentication andauthorization.
This page describes how to configure service accounts so that you can attachthem to resources.
Before you begin
Enable the IAM and Resource Manager APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Make sure you understandhow service accounts work inIAM.
Required roles
To get the permission that you need to attach a service account to a resource, ask your administrator to grant you theService Account User (roles/iam.serviceAccountUser) IAM role on the service account. For more information about granting roles, seeManage access to projects, folders, and organizations.
This predefined role contains the iam.serviceAccounts.actAs permission, which is required to attach a service account to a resource.
You might also be able to get this permission withcustom roles or otherpredefined roles.
Configure your organization policies
Depending on the location of the service account that you want to attach to theresource, you might need to update your project'sorganizationpolicies before attaching the service account:
If the service account is in the same project as the resource that you want toattach it to, then you don't need to update your project's organizationpolicies.
If the service account is in a different project than the resource that youwant to attach it to, then you need to update the organization policies forthe project containing the service account. For details, seeEnable serviceaccounts to be attached across projects on thispage.
This might be the case if, for example, youcreate all of your serviceaccounts in a single project.
Configure the service account
Before you attach a service account to a resource, you must configure theservice account. This process differs depending on whether the service accountand the resource are in the same project or in different projects. After youconfigure the service account, you can create the resource and attach theservice account to that resource.
Configure for a resource in the same project
Before you attach a service account to another resource in the same project,grant roles to the service account so it canaccess the appropriate resources, just as you would grant roles to any otherprincipal.
Configure for a resource in a different project
In some cases, you might need to attach a service account to a resource that islocated in a different project. For example, if youcreate all of your service accounts in a single project, youmight need to attach one of them to a new resource in a different project.
Before you attach a service account to a resource in another project, do thefollowing:
- In the project where the service account is located, follow the steps onthis page toenable service accounts to be attached across projects.
- Identify the project where you will create the resource.
Identify the type of resource that you will attach the service account to,as well as the service that owns that type of resource.
For example, if you are creating a Pub/Sub subscription, thenPub/Sub is the service that owns the resource.
Find the email address of the service agent for the service.
Different services use different service agents. For details, seeService agents.
Note: Some services, including Dataflow, Dataproc, andGoogle Kubernetes Engine, can create Compute Engine instances or depend onCompute Engine in another way. For these services, you must find theemail addresses for multiple service agents: one for Compute Engine,and another for the service that deploys the instances.Grant the Service Account Token Creator role(
roles/iam.serviceAccountTokenCreator) to the service agents:Console
In the Google Cloud console, go to theService accounts page.
Select the project that owns the service account that you will attach to aresource.
Click the email address of the service account that you will attach to aresource.
Go to thePrincipals with access tab.
ClickGrant access, and then enter the email address of the service agent.
ClickSelect a role, type
Service Account Token Creator, and clickthe role.ClickSave to save your changes.
Optional: If you need to grant the role to another service agent, repeat theprevious steps.
gcloud
Use the
gcloud iam service-accounts add-iam-policy-bindingcommand:gcloudiamservice-accountsadd-iam-policy-binding\SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com\--member=serviceAccount:SERVICE_AGENT_EMAIL\--role=roles/iam.serviceAccountTokenCreator
Replace the following values:
SERVICE_ACCOUNT_NAME: The name of the user-managedservice account that you are attaching to a resource.PROJECT_ID: The project ID where the user-managedservice account is located.SERVICE_AGENT_EMAIL: The email address for the serviceagent.
The command prints the updated allow policy for the user-managed serviceaccount.
Optional: If you need to grant the role to another service agent, run thecommand again.
REST
To grant this role, use the read-modify-write pattern to update the allow policyfor your user-managed service account.
First, read the allow policy for the user-managed service account:
The
projects.serviceAccounts.getIamPolicymethod returns the 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.USER_SA_NAME: The name of the user-managed service account that you are binding to a resource.
HTTP method and URL:
POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/USER_SA_NAME@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy
Request JSON body:
{ "requestedPolicyVersion": 3}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 thegcloudCLI with your user account by runninggcloud initorgcloud auth login, or by usingCloud Shell, which automatically logs you into thegcloudCLI . You can check the currently active account by runninggcloud auth list.Save the request body in a file named
request.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/USER_SA_NAME@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy"PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloudCLI with your user account by runninggcloud initorgcloud auth login. You can check the currently active account by runninggcloud auth list.Save the request body in a file named
request.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/USER_SA_NAME@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy" | Select-Object -Expand ContentAPIs 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.
You should receive a JSON response similar to the following:
{ "version": 1, "etag": "BwWl3KCTUMY=", "bindings": [ { "role": "roles/iam.serviceAccountUser", "members": [ "serviceAccount:my-service-account@my-project.iam.gserviceaccount.com" ] } ]}Next, modify the allow policy to grant the Service Account Token Creator roleto the service agent.
{"version":1,"etag":"BwWl3KCTUMY=","bindings":[{"role":"roles/iam.serviceAccountTokenCreator","members":["serviceAccount:SERVICE_AGENT_EMAIL"]},{"role":"roles/iam.serviceAccountUser","members":["serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com"]}]}
Replace the following:
SERVICE_AGENT_EMAIL: The email address for theservice agentSERVICE_ACCOUNT_NAME: The name of the user-managedservice account.PROJECT_ID: The project ID where the user-managedservice account is located.
membersarray.Finally, write the updated allow policy:
The
projects.serviceAccounts.setIamPolicymethod updates the allow policy for your 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.USER_SERVICE_ACCOUNT_NAME: The name of the user-managed service account that you are binding to a resource.SERVICE_AGENT_EMAIL: The email address of the service agent that will create access tokens for your user-managed service account.
HTTP method and URL:
POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy
Request JSON body:
{ "policy": { "version": 1, "etag": "BwWl3KCTUMY=", "bindings": [ { "role": "roles/iam.serviceAccountTokenCreator", "members": [ "serviceAccount:SERVICE_AGENT_EMAIL" ] }, { "role": "roles/iam.serviceAccountUser", "members": [ "serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" ] } ] }}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 thegcloudCLI with your user account by runninggcloud initorgcloud auth login, or by usingCloud Shell, which automatically logs you into thegcloudCLI . You can check the currently active account by runninggcloud auth list.Save the request body in a file named
request.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/SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy"PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloudCLI with your user account by runninggcloud initorgcloud auth login. You can check the currently active account by runninggcloud auth list.Save the request body in a file named
request.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/SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy" | Select-Object -Expand ContentAPIs 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.
You should receive a JSON response similar to the following:
{ "version": 1, "etag": "BwWo331TkHE=", "bindings": [ { "role": "roles/iam.serviceAccountTokenCreator", "members": [ "serviceAccount:SERVICE_AGENT_EMAIL" ] }, { "role": "roles/iam.serviceAccountUser", "members": [ "serviceAccount:my-service-account@my-project.iam.gserviceaccount.com" ] } ]}
Attach the service account to a resource
After you configure the user-managed service account, you can create a newresource and attach the service account to that resource. Make sure you createthe new resource in the appropriate project.
In most cases, you must attach a service account to a resource when you createthat resource. After the resource is created, you cannot change which serviceaccount is attached to the resource. Compute Engine instances are anexception to this rule; you canchange which service account is attached to an instanceas needed.
See the instructions for the type of resource that you want to create:
| Attaching a service account when creating a resource | |
|---|---|
| AI Platform Prediction | Model versions |
| AI Platform Training | Jobs |
| App Engine standard environment | App versions |
| App Engine flexible environment | App versions |
| Cloud Composer | Environments |
| Cloud Run functions | Cloud Run function |
| Cloud Run | Services |
| Cloud Scheduler | Jobs |
| Cloud Source Repositories |
|
| Compute Engine | |
| Dataproc | Clusters |
| Google Kubernetes Engine | |
| Notebooks | Notebook instances |
| Pub/Sub | Subscriptions |
After you have created the resource and attached the service account to thatresource, you can grant roles to the service account so it can access theappropriate resources. This process is the same as granting a role to any otherprincipal.
To learn how to grant roles, seeGranting, changing, and revoking access to resources.
Enable service accounts to be attached across projects
If you want to let users attach service accounts in one project to resources inanother project, you must update theorganization policies for theproject that contains the service accounts. Check the followingbooleanconstraints in the organization policies for that project:
Important: After you update your organization policies, we strongly discourageyou from undoing the changes, especially in production environments. If you undothe changes, your Google Cloud resources might not work correctly.Ensure that the
iam.disableCrossProjectServiceAccountUsagebooleanconstraintis not enforced for the project.This boolean constraint controls whether you can attach a service account toa resource in another project. It is enforced by default and can only beconfigured at the project level, not the folder or organization level.
When this constraint is not enforced, IAM adds aproject lien that prevents the project from being deleted.This lien has the origin
iam.googleapis.com/cross-project-service-accounts. We strongly discourageyou from deleting this lien.Recommended: Ensure that the
iam.restrictCrossProjectServiceAccountLienRemovalboolean constraintisenforced for the project.This boolean constraint ensures that principals can remove the project lienonly if they have the
resourcemanager.projects.updateLienspermission atthe organization level. If this constraint is not enforced, principals canremove the project lien if they have this permission at the project level.
To learn how to view or change a boolean constraint in an organizationpolicy, seeCreating and managing organization policies.
Disable service accounts from being attached across projects
If you previouslyenabled service accounts to be attached acrossprojects, we strongly discourage you fromdisabling this feature, especially in production environments.
Caution: If you disable service accounts from being attached across projects,your Google Cloud resources might not work correctly.Specifically, in the project where your service accounts are located, youshouldn't make any of these changes:
- Don't update the project's organization policies toenforce the
iam.disableCrossProjectServiceAccountUsageboolean constraint. - Don't update the project's organization policies tonot enforce the
iam.restrictCrossProjectServiceAccountLienRemovalboolean constraint. - Don't remove theproject lien with the origin
iam.googleapis.com/cross-project-service-accounts, which prevents you fromdeleting the project. - Don't delete the project.
If you are willing to accept the risk of disabling this feature, you can reduceyour risk bydisabling the service accounts that you are usingacross projects, then monitoring your Google Cloud environment for issues.If you see any issues, you canre-enable the service accounts. Ifyou don't see any issues, then you might not have any Google Cloudresources that depend on a service account in a different project.
Audit logs for attaching service accounts
When a principal uses theiam.serviceAccounts.actAs permission to attach aservice account to a resource, IAM generates an audit log. Thisaudit log contains the following information:
- The email address of the principal that attached the service account to theresource
- Details about the service account that was attached to the resource
For a list of resources that you can attach service accounts to, seeAttach theservice account to the new resource on this page.
For an example of this type of audit log, seeLogs for using theiam.serviceAccounts.actAs permission. To learn more aboutaudit logs in general, seeCloud Audit Logs overview.
What's next
- Find out how toattach a service account to a Compute Engineinstance.
- Review and applybest practices for securing service accounts.
- Learn more aboutaudit logging for IAM.
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 2025-12-15 UTC.