Change the attached service account Stay organized with collections Save and categorize content based on your preferences.
This document explains how to configure an existing virtual machine (VM) to usea different service account. A service account is a special kind ofaccount typically used by an application or compute workload to makeauthorized API calls.
Service accounts are needed for scenarios where a workload, such as a customapplication, needs to access Google Cloud resources or perform actions withoutend-user involvement. For more information about when to use service accounts,seeBest practices for using service accounts.
If you have applications that need to make calls to Google Cloud APIs,Google recommends that you attach a user-managed service account to the VM on which theapplication or workload is running. Then, you grant the service accountIAM roles, which gives the service account–and,by extension, applications running on the VM–access toGoogle Cloud resources.
Note: When a user connects to a VM, that user can use all of the IAM permissions granted to the service account attached to the VM.Before you begin
- If you haven't already, set upauthentication. Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.- Set a default region and zone.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Required roles
To get the permissions that you need to configure service accounts on your VM, ask your administrator to grant you theCompute Instance Admin (v1) (roles/compute.instanceAdmin.v1) IAM role on the VM or your project. For more information about granting roles, seeManage access to projects, folders, and organizations.
This predefined role contains the permissions required to configure service accounts on your VM. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to configure service accounts on your VM:
compute.instances.setServiceAccountcompute.instances.stopcompute.instances.start
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Overview
It is recommended that you configure service accounts for your VMs asfollows:
- Create a new user-managed service account rather than using the Compute Engine default service account, and grant IAM roles to that service account for only the resources and operations that it needs.
- Attach the service account to your VM.
- Set the cloud platform (
https://www.googleapis.com/auth/cloud-platform) scope on your VM. This allows the VM's service account to call the Google Cloud APIs that it has permission to use.- If you specify the service account by using the Google Cloud console, set the service account's access scope toAllow full access to all Cloud APIs.
- If you specify the service account by using the Google Cloud CLI or Compute Engine API, you can use the
scopesparameter to set the access scope.
Set up the service account
You can either create a user-managed service account or use theCompute Engine default service account. A user-managed service accountis recommended.
For the selected service account, ensure that the requiredIdentity and Access Management (IAM) roles are assigned.
User-managed
If you don't already have a user-managed service account, create a service account.For detailed instruction, seeSet up a service account.
Default
If you are familiar with the Compute Engine default serviceaccount and want to use the credentials provided by the default serviceaccount instead of creating new service accounts, you can grantIAM roles to the default service account.
Before you assign IAM roles to the default service account,note that:
Granting an IAM role to the default service accountaffects all VMs that are running as the default service account.For example, if you grant the default service account the
roles/storage.objectAdminrole, all VMs running as the default serviceaccount with the required access scopes will have permissions granted bytheroles/storage.objectAdminrole.Likewise, if you limit access by omitting certain roles, this affectsall VMs running as the default service account.Depending on your organization policy configuration, the default service account might automatically be granted theEditor role on your project. We strongly recommend that you disable the automatic role grant by enforcing the
iam.automaticIamGrantsForDefaultServiceAccountsorganization policy constraint. If you created your organization after May 3, 2024, this constraint is enforced by default.If you disable the automatic role grant, you must decide which roles to grant to the default service accounts, and thengrant these roles yourself.
If the default service account already has the Editor role, we recommend that you replace the Editor role with less permissive roles.To safely modify the service account's roles, usePolicy Simulator to see the impact of the change, and thengrant and revoke the appropriate roles.
If you are unsure about granting IAM roles to the default service account,create a new user-managed service account instead.
Caution: If you have existing VMs that use the default service account, modifying the default service account's roles will prevent those VMs from accessing some resources.Attach the service account and update the access scope
To change a VM's service account and access scopes, you must first stop the VM.After you make the necessary changes, you can restart the VM.
Note: When updating a VM instance, you might encounter aSupplied fingerprintdoes not match current metadata fingerprint error. This issue can happen if theVM's metadata was updated by another process since you last refreshed the page.For a detailed explanation and workaround, seeTroubleshoot VM updates.If the service account you want to attach to the VM is in a different projectthan the VM, you mustconfigure the service account for a resource in a different project.
Use one of the following methods to change the service account and access scopeson your VM.
Console
Go to theVM instances page.
Click the VM instance name for which you want to change the service account.
ClickStop. If there isnoStop option, clickMore actions >Stop.Wait for the VM to be stopped.
ClickEdit.
Scroll down to theService Account section.
From the drop-down list, select the service account to assign to theVM.
- If you choose a user-managed service account, the VM's access scopedefaults to the recommended
cloud-platformscope. If you need adifferent scope for your user-managed service account,use the gcloud CLI or Compute Engine API to attach the serviceaccount. - If you choose the Compute Engine default service account, you canmodify its access scopes in the Google Cloud console.
- To change scopes, in theAccess scopes section, selectSetaccess for each API and set the appropriate scopes for yourneeds.
- Recommended If you're not sure of the proper access scopesto set, chooseAllow full access to all Cloud APIs and thenmake sure torestrict access by setting IAM roles on the service account.
- If you choose a user-managed service account, the VM's access scopedefaults to the recommended
ClickSave to save your changes.
ClickStart/Resume to restart the VM.
gcloud
Stop the VM by using the
instances stopcommand.ReplaceVM_NAMEwith the name of your VM instance.gcloud compute instances stopVM_NAME
Attach the service account. To attach the service account, use the
instances set-service-accountcommandand provide the VM name, the service account email, and the desiredscopes. For more information about setting access scopes, seeBest practices.gcloud compute instances set-service-accountVM_NAME \ --service-account=SERVICE_ACCOUNT_EMAIL \ --scopes=SCOPES
Replace the following:
SERVICE_ACCOUNT_EMAIL: the email address forthe service account that you created.For example:my-sa-123@my-project-123.iam.gserviceaccount.com. Toview the email address, seeListing service accounts.If you want to remove the service account from the VM, use the
--no-service-accountflag.VM_NAME: the name of the VM instance.SCOPES: a comma-separated list ofscope URIs or aliasesprovided in the description for the--scopesflag.If you want to remove all scopes for the VM, use the
--no-scopesflaginstead.
For example, the following command assigns the service account
my-sa-123@my-project-123.iam.gserviceaccount.comto a VM calledexample-instance and sets access scopes on that VM to allowread/write access to Compute Engine and read-only access toCloud Storage:gcloud compute instances set-service-account example-instance \ --service-account=my-sa-123@my-project-123.iam.gserviceaccount.com \ --scopes=compute-rw,storage-ro
Start the VM by using the
instances startcommand.ReplaceVM_NAMEwith the name of your VM instance.gcloud compute instances startVM_NAME
REST
Stop the VM by making a
POSTrequest using theinstances.stopmethod:POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/stop
Replace the following:
PROJECT_ID: the project your VM is inZONE: the zone where your VM is locatedVM_NAME: the name of the VM you want to stop
Attach the service account by making a
POSTrequest to thesetServiceAccountmethod:POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/setServiceAccount{ "email": "SERVICE_ACCOUNT_EMAIL", "scopes": [ "SCOPE_URI", "SCOPE_URI", ... ]}Replace the following:
PROJECT_ID: the project ID for this request.ZONE: the zone where this VM belongs to.VM_NAME: the name of the VM.SERVICE_ACCOUNT_EMAIL: the email address forthe service account that you created.For example:my-sa-123@my-project-123.iam.gserviceaccount.com. Toview the email address, seeListing service accounts.SCOPE_URI: the requiredscope URI.
For example, the following request uses the service accountemail
my-sa-123@my-project-123.iam.gserviceaccount.comand sets aCloud Storage and BigQuery scope:POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/setServiceAccount{ "email": "my-sa-123@my-project-123.iam.gserviceaccount.com", "scopes": [ "https://www.googleapis.com/auth/bigquery", "https://www.googleapis.com/auth/devstorage.read_only" ]}Start the VM by constructing a
POSTrequest using theinstances.startmethod:POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/start
Replace the following:
PROJECT_ID: the project your VM is inZONE: the zone where your VM is locatedVM_NAME: the name of the VM you want to start
View the service account that is used by a VM
To view all the service accounts in a project, seeListing service accounts.
If you need to identify the service account that is being used by a VM,complete one of the following procedures:
console
Go to theVM instances page.
Click the VM instance name for which you want to change the service account.
Go to theAPI and identity management section. This sections displaysthe service account and access scope that is used by the VM.
gcloud
Run thegcloud compute instances describe command:
gcloud compute instances describeVM_NAME \ --format json
The output is similar to the following:
{ ... "serviceAccounts":[ { "email":"123845678986-compute@developer.gserviceaccount.com", "scopes":[ "https://www.googleapis.com/auth/devstorage.full_control" ] } ] ... }If the VM isn't using a service account, you receive a responsewithout theserviceAccounts property.
Metadata Server
Query themetadata server from within the VMitself. Make a request tohttp://metadata.google.internal/computeMetadata/v1/instance/service-accounts/:
user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/" \-H "Metadata-Flavor: Google"If you enabled one or more service accounts when you created the instance,thiscurl command returns output similar to the following:
123845678986-compute@developer.gserviceaccount.com/default/
If the instance isn't using a service account, you receive an emptyresponse.
Best practices
- Limit the privileges of service accountsand regularly check your service account permissions to make sure they areup-to-date.
- Delete service accounts with caution. Make sure your critical applicationsare no longer using a service account before deleting it. If you're not surewhether a service account is being used, we recommenddisabling the serviceaccount instead ofdeleting it. Disabled service accounts can be re-enabled if they are stillneeded.
- Mitigate the security risks for your service account. For more information,seeBest practices for working with serviceaccounts.
What's next?
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.