Create a VM that uses a user-managed service account Stay organized with collections Save and categorize content based on your preferences.
This document explains how to create a virtual machine (VM) instance that isconfigured to use a user-managed service account. A service account is a specialkind of account 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.
Terraform
To use the Terraform samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
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.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
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.
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 create VMs that use service accounts, ask your administrator to grant you the following IAM roles on the project:
- Compute Instance Admin (v1) (
roles/compute.instanceAdmin.v1) - Create Service Accounts (
roles/iam.serviceAccountCreator) - Project IAM Admin (
roles/resourcemanager.projectIamAdmin)
For more information about granting roles, seeManage access to projects, folders, and organizations.
These predefined roles contain the permissions required to create VMs that use service accounts. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to create VMs that use service accounts:
- To create service accounts: All the permissions in the
iam.serviceAccountCreatorrole - To grant permissions to the service account: All the permissions in the
resourcemanager.projectIamAdminrole - To create VMs:
compute.instances.createon the project- To use a custom image to create the VM:
compute.images.useReadOnlyon the image - To use a snapshot to create the VM:
compute.snapshots.useReadOnlyon the snapshot - To use an instance template to create the VM:
compute.instanceTemplates.useReadOnlyon the instance template - To assign alegacy network to the VM:
compute.networks.useon the project - To specify a static IP address for the VM:
compute.addresses.useon the project - To assign an external IP address to the VM when using a legacy network:
compute.networks.useExternalIpon the project - To specify a subnet for the VM:
compute.subnetworks.useon the project or on the chosen subnet - To assign an external IP address to the VM when using a VPC network:
compute.subnetworks.useExternalIpon the project or on the chosen subnet - To set VM instance metadata for the VM:
compute.instances.setMetadataon the project - To set tags for the VM:
compute.instances.setTagson the VM - To set labels for the VM:
compute.instances.setLabelson the VM - To set a service account for the VM to use:
compute.instances.setServiceAccounton the VM - To create a new disk for the VM:
compute.disks.createon the project - To attach an existing disk in read-only or read-write mode:
compute.disks.useon the disk - To attach an existing disk in read-only mode:
compute.disks.useReadOnlyon the disk
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 a service account
Create a service account and assign the required IAM roles.Assign as many or as little IAM roles as needed. You can modifythe IAM roles on your service account as needed.
Google recommends that youlimit the privileges of service accountsand regularly check your service account permissions to make sure they areup-to-date.
Use one of the following methods to set up the service account.
Console
- Ensure that you have the Create Service Accounts IAM role (
In the Google Cloud console, go to theCreate service account page.
Go to Create service account- Select your project.
In theService account name field, enter a name. The Google Cloud console fills in theService account ID field based on this name.
In theService account description field, enter a description. For example,
Service account for quickstart.- ClickCreate and continue.
Grant the required roles to the service account.
To grant a role, find theSelect a role list, then select the role.
To grant additional roles, clickAdd another role and add each additional role.
Note: TheRole field affects which resources the service account can access in your project. You can revoke these roles or grant additional roles later. In production environments, do not grant the Owner, Editor, or Viewer roles. Instead, grant apredefined role orcustom role that meets your needs.- ClickContinue.
In theService account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.
This is typically the email address for a Google Account.
ClickDone to finish creating the service account.
roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin).Learn how to grant roles.gcloud
- Ensure that you have the Create Service Accounts IAM role (
In the Google Cloud console, go to theCreate service account page.
Go to Create service account- Select your project.
In theService account name field, enter a name. The Google Cloud console fills in theService account ID field based on this name.
In theService account description field, enter a description. For example,
Service account for quickstart.- ClickCreate and continue.
Grant the required roles to the service account.
To grant a role, find theSelect a role list, then select the role.
To grant additional roles, clickAdd another role and add each additional role.
Note: TheRole field affects which resources the service account can access in your project. You can revoke these roles or grant additional roles later. In production environments, do not grant the Owner, Editor, or Viewer roles. Instead, grant apredefined role orcustom role that meets your needs.- ClickContinue.
In theService account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.
This is typically the email address for a Google Account.
ClickDone to finish creating the service account.
roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin).Learn how to grant roles.Terraform
To create a service account, you can use thegoogle_service_accountresource.
resource "google_service_account" "default" { account_id = "service-account-id" display_name = "Service Account"}Remember to replace the placeholder values for theaccount_id and thedisplay_name attributes.
To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands.
Create a VM and attach the service account
After you create the service account, create a VM and attach the service accountthat you created in the previous section. Also set the VM's access scope tocloud-platform.
If you already have an existing VM and you want to configure that VM to use adifferent service account, seeChange the attached service account.
Use one of the following methods to create a VM and attach the service account.
Console
In the Google Cloud console, go to theCreate an instance page.
To attach a service account, do the following:
- In the navigation menu, clickSecurity.
- In theService account list, select the service account that youcreated.
- ForAccess scopes, selectAllow full access to all Cloud APIs.
Optional: Specify other configuration options. For more information, seeConfiguration options during instance creation.
To create and start the instance, clickCreate.
gcloud
To create a new VM instance and configure it to use a custom service accountby using the Google Cloud CLI, use thegcloud compute instances createcommand and provide theservice account email and thecloud-platform access scope to the VMinstance.
gcloud compute instances createVM_NAME \ --service-account=SERVICE_ACCOUNT_EMAIL \ --scopes=https://www.googleapis.com/auth/cloud-platform
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. To view theemail address, seeListing service accounts.VM_NAME: the name of the VM instance.
For example:
gcloud compute instances create example-vm \ --service-account 123-my-sa@my-project-123.iam.gserviceaccount.com \ --scopes=https://www.googleapis.com/auth/cloud-platform
You can also specify the scope using the alias:--scopes=cloud-platform.These aliases are recognized only by the gcloud CLI. The APIand other libraries don't recognize these aliases, so you must specify thefull scope URI.
Terraform
To set up a new VM to use a service account, you can use thegoogle_compute_instanceresource.
resource "google_compute_instance" "default" { name = "my-test-vm" machine_type = "n1-standard-1" zone = "us-central1-a" boot_disk { initialize_params { image = "debian-cloud/debian-11" } } // Local SSD disk scratch_disk { interface = "SCSI" } network_interface { network = "default" access_config { // Ephemeral public IP } } service_account { # Google recommends custom service accounts with `cloud-platform` scope with # specific permissions granted via IAM Roles. # This approach lets you avoid embedding secret keys or user credentials # in your instance, image, or app code email = google_service_account.default.email scopes = ["cloud-platform"] }}REST
Use theinstances.insertmethod to create the VMand specify the service account email and access scope for the VM instance.
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances{ "machineType":"zones/MACHINE_TYPE_ZONE/machineTypes/MACHINE_TYPE", "name":"VM_NAME", "disks":[ { "initializeParams":{ "sourceImage":"projects/IMAGE_PROJECT/global/images/IMAGE" }, "boot":true } ], "networkInterfaces":[ { "network":"global/networks/NETWORK_NAME" } ], "serviceAccounts": [ { "email": "SERVICE_ACCOUNT_EMAIL", "scopes": ["https://www.googleapis.com/auth/cloud-platform"] } ], "shieldedInstanceConfig":{ "enableSecureBoot":"ENABLE_SECURE_BOOT" }}
Replace the following:
PROJECT_ID: ID of the project to create the VM inZONE: zone to create the VM inMACHINE_TYPE_ZONE: zone containing the machine type to use for the new VMMACHINE_TYPE: machine type,predefined orcustom, for the new VMVM_NAME:name of the new VMIMAGE_PROJECT:project containing the image
For example, if you specifydebian-10as the image family, specifydebian-cloudas the image project.IMAGE: specify one of the following:IMAGE: a specific version of a public imageFor example,
"sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200309"IMAGE_FAMILY: animage familyThis creates the VM from the most recent, non-deprecated OS image. For example, if you specify
"sourceImage": "projects/debian-cloud/global/images/family/debian-10", Compute Engine creates a VM from the latest version of the OS image in theDebian 10image family.
NETWORK_NAME: the VPC network that you want to use for the VM. You can specifydefaultto use your default network.SERVICE_ACCOUNT_EMAIL: the email address for the service account that you created. For example:my-sa-123@my-project-123.iam.gserviceaccount.com. To view the email address, seeobtain a service account email.ENABLE_SECURE_BOOT: Optional: If you chose an image that supportsShielded VM features, Compute Engine, by default, enables thevirtual trusted platform module (vTPM) andintegrity monitoring. Compute Engine does not enableSecure Boot by default.If you specify
trueforenableSecureBoot, Compute Engine creates a VM with all three Shielded VM features enabled. After Compute Engine starts your VM, tomodify Shielded VM options, you must stop the VM.
Access and use other Google Cloud services
After your VM is configured to use the service account, applications can thenuse the service account to authenticate. The most common method is toauthenticate by usingApplication Default Credentialsand a client library. Some Google Cloud tools such as thegcloud CLI are able to automatically use the serviceaccount to access Google Cloud APIs from a VM. For more information,seeAuthenticate workloads using service accounts.
If a service account is deleted, applications will no longer have access toGoogle Cloud resources through that service account. If you delete the defaultApp Engine and Compute Engine service accounts, your VMs will no longer haveaccess to resources in the project. If you're not sure whether a serviceaccount is being used, Google recommendsdisabling the service accountbefore deleting it. Disabled service accounts can be re-enabled if they arestill needed.
Example: Access Cloud Storage resources from your VM
After you have configured your VM to use a service account that has thestorage.admin role, you can use tools such as the gcloud CLIto manage files that you have stored on Cloud Storage. To access yourCloud Storage resources, complete the following:
Ensure that the service account that is attached to your VM has the
roles/storage.adminrole.If your VM uses a custom OS image,install the gcloud CLI. By default, the gcloud CLI is installedon most public OS images that are provided by Google Cloud.
Connect to the VM.
From the VM, use theGoogle Cloud CLI tomanage your Cloud Storage resources.
What's next?
- Learn how toauthenticate workloads using service accounts.
- Learn how tochange the service account attached to a VM.
- Learn how tolist and edit service accounts.
- Review thebest practices for working with service accountsand mitigate security risks.
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.