Assign a service account for a VM, add access scopes, and set up the VM to run as a service account.

## Explore further


For detailed documentation that includes this code sample, see the following:

- [Create a VM that uses a user-managed service account](https://docs.cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances)

## Code sample

### Terraform


To learn how to apply or remove a Terraform configuration, see
[Basic Terraform commands](https://docs.cloud.google.com/docs/terraform/basic-commands).


For more information, see the
[Terraform provider reference documentation](https://registry.terraform.io/providers/hashicorp/google/latest/docs).

    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-13"
        }
      }

      // 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"]
      }
    }

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=computeengine).