Attach service accounts to resources  |  IAM Documentation  |  Google Cloud (2024)

For some Google Cloud resources, you can specify a user-managed service account that theresource uses as its default identity. This process is known as attaching the serviceaccount to the resource, or associating 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 you attach aservice account to a Compute Engine instance, and the applications on the instance use a client 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.

    Enable the APIs

  • Make sure you understand how 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 the Service Account User (roles/iam.serviceAccountUser) IAM role on the service account. For more information about granting roles, see Manage 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 with custom roles or other predefined roles.

Attach a service account to a resource

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.

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:

  1. In the project where the service account is located, follow the steps onthis page toenable service accounts to be attached across projects.
  2. Identify the project where you will create the resource.
  3. 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.

  4. Find the email address of the service agent for the service.

    Different services use different service agents. For details, seeService agents.

  5. Grant the Service Account Token Creator role(roles/iam.serviceAccountTokenCreator) to the service agents:

    Console

    1. In the Google Cloud console, go to the Service accounts page.

      Go to Service accounts

    2. Select the project that owns the service account that you will attach to aresource.

    3. Click the email address of the service account that you will attach to aresource.

    4. Go to the Permissions tab and find the section Principals with accessto this service account.

    5. Click person_addGrant access, and then enter the email address of the service agent.

    6. Click Select a role, type Service Account Token Creator, and clickthe role.

    7. Click Save to save your changes.

    8. Optional: If you need to grant the role to another service agent, repeat theprevious steps.

    gcloud

    Use thegcloud iam service-accounts add-iam-policy-bindingcommand:

    gcloud iam service-accounts add-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.getIamPolicy method 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, like my-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)

    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)

    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 Content

    APIs Explorer (browser)

    Copy the request body and open the method 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 click Execute.

    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 agent
    • SERVICE_ACCOUNT_NAME: The name of the user-managedservice account.
    • PROJECT_ID: The project ID where the user-managedservice account is located.

    Finally, write the updated allow policy:

    The projects.serviceAccounts.setIamPolicy method 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, like my-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)

    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)

    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 Content

    APIs Explorer (browser)

    Copy the request body and open the method 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 click Execute.

    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 the new 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.

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 Life Sciences Pipelines
Cloud Run Services
Cloud Scheduler Jobs
Cloud Source Repositories
  • Project configs
  • Pub/Sub configuration for repos
Compute Engine
  • Instances
  • Instance templates
Dataflow Jobs
Datalab Instances
Dataproc Clusters
Eventarc Triggers
Google Kubernetes Engine
  • Clusters
  • Node pools
Notebooks Notebook instances
Pub/Sub Subscriptions
Vertex AI
  • Custom jobs
  • Deployed models
  • Hyperparameter tuning jobs
  • Training pipelines
Workflows Workflows

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.

Attach a service account to a resource in another project

By default, you cannot create a service account in one project and attach it toa resource in another project. If you want to keep all of your service accountsin one project, you must update the organization policy for thatproject.

Enable service accounts to be attached across projects

To let users attach service accounts in one project to resources in anotherproject, check the following boolean constraints in theorganization policy for the project where your service accounts are located:

  • Ensure that the iam.disableCrossProjectServiceAccountUsage booleanconstraint is not enforced for the project.

    This boolean constraint controls whether you can attach a service account toa resource in another project. The constraint is enforced by default.

    When this constraint is not enforced, IAM adds aproject lien that prevents the project from being deleted.This lien has the originiam.googleapis.com/cross-project-service-accounts. We strongly discourageyou from deleting this lien.

  • Recommended: Ensure that theiam.restrictCrossProjectServiceAccountLienRemoval boolean constraint isenforced for the project.

    This boolean constraint ensures that principals can remove the project lienonly if they have the resourcemanager.projects.updateLiens permission 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, see Creating and managing organization policies.

Disable service accounts from being attached across projects

If you previously enabled service accounts to be attached acrossprojects, we strongly discourage you fromdisabling this feature, especially in production environments.

Specifically, in the project where your service accounts are located, youshouldn't make any of these changes:

  • Don't update the project's organization policy to enforce theiam.disableCrossProjectServiceAccountUsage boolean constraint.
  • Don't update the project's organization policy to not enforce theiam.restrictCrossProjectServiceAccountLienRemoval boolean constraint.
  • Don't remove the project lien with the originiam.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 by disabling the service accounts that you are usingacross projects, then monitoring your Google Cloud environment for issues.If you see any issues, you can re-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 the iam.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, see Attach theservice account to the new resource on this page.

For an example of this type of audit log, see Logs for using theiam.serviceAccounts.actAs permission. To learn more aboutaudit logs in general, see Cloud Audit Logs overview.

What's next

  • Find out how to attach a service account to a Compute Engineinstance.
  • Review and apply best practices for securing service accounts.
  • Learn more about audit logging for IAM.
Attach service accounts to resources  |  IAM Documentation  |  Google Cloud (2024)

FAQs

How do I add a service account to my GCP project? ›

  1. In the Google Cloud console, go to the Create service account page. ...
  2. Select a Google Cloud project.
  3. Enter a service account name to display in the Google Cloud console. ...
  4. Optional: Enter a description of the service account.
  5. If you don't want to set access controls now, click Done to finish creating the service account.

What is the difference between user account and service account in Google Cloud? ›

Service accounts differ from normal user accounts in multiple ways: They don't have a password and can't be used for browser-based sign-in. They're created and managed as a resource that belongs to a Google Cloud project. In contrast, users are managed in a Cloud Identity or Google Workspace account.

How to list service account in GCP? ›

Listing service accounts
  1. In the Google Cloud console, go to the Service accounts page. Go to Service accounts.
  2. Select a project. The Service accounts page lists all of the user-managed service accounts in the project you selected.

Why is a service account required in GCP? ›

Applications use service accounts to make authorized API calls by authenticating as either the service account itself, or as Google Workspace or Cloud Identity users through domain-wide delegation.

How do I add an account as a service? ›

Enable service log on permission for Run As accounts

Go to Administrative Tools and select Local Security Policy. Expand Local Policy and select User Rights Assignment. In the right pane, right-click Log on as a service and select Properties. Select Add User or Group option to add the new user.

What is an example of a service account? ›

An example of a service account is a Google Cloud Platform (GCP) service account. GCP service accounts are used to authenticate applications and services that run on GCP. They allow the application or service to interact with other GCP resources, such as Google Cloud Storage or Google BigQuery.

What are service accounts in cloud? ›

A service account is a special kind of account used by an application or compute workload, rather than a person. Service accounts are managed by Identity and Access Management (IAM).

How to give permissions to service account in GCP? ›

Grant a single role
  1. In the Google Cloud console, go to the Service Accounts page. ...
  2. Select a project.
  3. Click the email address of the service account.
  4. Go to the Permissions tab and find the section Principals with access to this service account.
  5. Select a principal to grant a role to:

What is the default service account in GCP? ›

Default service accounts – This type of service account is created by Google Cloud and can execute cloud API calls to various resources in the project. Default service accounts are automatically given the Editor role when created.

What is the limit on number of service accounts in GCP? ›

Quotas
Default quotas
Service accounts
Number of service accounts100 per project
Privileged Access Manager API
Entitlement write requests (for example, creating, updating, or deleting an entitlement)100 per project per minute 100 per organization per minute
39 more rows

What are service account keys in GCP? ›

Like a username and password, service account keys are a form of credential. If a user can access a valid service account key, they can use it to authenticate and access the resources the respective service account has been granted access to.

Which method would you use to create service accounts in Google Cloud? ›

Create a service account
  1. Step 1: Create a project. Go to Google Cloud and sign in as a super administrator. ...
  2. Step 2: Turn on the APIs for the service account. Check the box next to your new project. ...
  3. Step 3: Set up the OAuth consent screen. ...
  4. Step 4: Create the service account.

How do I give service account access to another project in GCP? ›

In the Google Cloud console, go to the IAM page. Select the project that owns the service account. Click person_add Grant access. In the New principals field, enter the email address of the principal.

What is the difference between GCP service account and API key? ›

The API keys authenticate for APIs that do not access personal data. The client id authenticates with your Google Account. The service account authenticates your application when you do not want to use the login data of your own account (or any real persons account).

How do I use a service account in cloud function? ›

Adding a user-managed service account at deployment
  1. Go to the Google Cloud console: ...
  2. Specify and configure the function however you would like.
  3. Click Runtime, build... to display additional settings.
  4. Select the Runtime tab.
  5. Click the Service account dropdown and select the desired service account.
  6. Click Next and Deploy.

How do I add users to my GCP project? ›

Open the console left side menu and select IAM & Admin. From the project list, choose the project that you want to add a member to. Click Add Member and provide an email address. You can add individuals or Google Groups as members, but every project must have at least one project member that is an individual.

How do I add a service provider to Google? ›

Add or edit services on Business Profile
  1. Go to your Business Profile. Learn how to find your profile.
  2. To find your services: With Google Search, select Edit services. With Google Maps, select Edit Profile. Services.
  3. Select the service you want to edit. To add a new service, select Add more services.
  4. Select Save.

How do I add a managed service account? ›

You create the gMSA in Active Directory and then configure the service that supports Managed Service Accounts. Use of the gMSA is scoped to any machine that is able to use LDAP to retrieve the gMSA's credentials. You can create a gMSA using the New-ADServiceAccount cmdlets that are part of the Active Directory module.

Top Articles
Antihistamines
USPS Package Intercept: FAQs
Foxy Roxxie Coomer
AllHere, praised for creating LAUSD’s $6M AI chatbot, files for bankruptcy
Truist Bank Near Here
It's Official: Sabrina Carpenter's Bangs Are Taking Over TikTok
Is pickleball Betts' next conquest? 'That's my jam'
Missing 2023 Showtimes Near Cinemark West Springfield 15 And Xd
Chase Bank Operating Hours
Craigslist Parsippany Nj Rooms For Rent
Bucks County Job Requisitions
City Of Spokane Code Enforcement
Garrick Joker'' Hastings Sentenced
Jasmine Put A Ring On It Age
Los Angeles Craigs List
Gwdonate Org
Burn Ban Map Oklahoma
Kris Carolla Obituary
2016 Ford Fusion Belt Diagram
Gon Deer Forum
Overton Funeral Home Waterloo Iowa
Driving Directions To Bed Bath & Beyond
라이키 유출
A Biomass Pyramid Of An Ecosystem Is Shown.Tertiary ConsumersSecondary ConsumersPrimary ConsumersProducersWhich
Craigslist Personals Jonesboro
Georgia Cash 3 Midday-Lottery Results & Winning Numbers
Toothio Login
Sherburne Refuge Bulldogs
Cpt 90677 Reimbursem*nt 2023
Craigslist Ludington Michigan
Pixel Combat Unblocked
1636 Pokemon Fire Red U Squirrels Download
Tottenham Blog Aggregator
Pfcu Chestnut Street
Metro By T Mobile Sign In
Does Iherb Accept Ebt
Synchrony Manage Account
In Polen und Tschechien droht Hochwasser - Brandenburg beobachtet Lage
Amc.santa Anita
Strange World Showtimes Near Century Stadium 25 And Xd
Spurs Basketball Reference
Port Huron Newspaper
Tacos Diego Hugoton Ks
Phmc.myloancare.com
Dying Light Mother's Day Roof
Das schönste Comeback des Jahres: Warum die Vengaboys nie wieder gehen dürfen
Mlb Hitting Streak Record Holder Crossword Clue
Random Warzone 2 Loadout Generator
Quest Diagnostics Mt Morris Appointment
What Time Do Papa John's Pizza Close
Fallout 76 Fox Locations
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 5926

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.