建立使用者代管的服務帳戶的 VM


本文說明如何建立虛擬機器 (VM) 執行個體,並將其設為使用使用者管理的服務帳戶。服務帳戶是一種特殊的帳戶,通常由應用程式或運算工作負載使用,用於發出授權的 API 呼叫。

在以下情境中,工作負載 (例如自訂應用程式) 需要存取 Google Cloud 資源或執行操作,但不需要使用者介入,就需要使用服務帳戶。如要進一步瞭解何時應使用服務帳戶,請參閱「使用服務帳戶的最佳做法」。

如果應用程式需要呼叫 Google Cloud API,Google 建議您將使用者管理的服務帳戶附加至執行應用程式或工作負載的 VM。接著,您會為服務帳戶授予 IAM 角色,讓服務帳戶 (以及在 VM 上執行的應用程式) 能夠存取Google Cloud 資源。

事前準備

  • 如果尚未設定,請先設定驗證機制。驗證是指驗證身分,以便存取 Google Cloud 服務和 API 的程序。如要在本機開發環境中執行程式碼或範例,您可以選取下列任一選項,向 Compute Engine 進行驗證:

    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

    1. After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    2. 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.

    1. Install the Google Cloud CLI.
    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      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.

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    For more information, see Authenticate for using REST in the Google Cloud authentication documentation.

必要的角色

如要取得建立使用服務帳戶的 VM 所需的權限,請要求管理員在專案中授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這些預先定義的角色包含建立使用服務帳戶的 VM 所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要建立使用服務帳戶的 VM,您必須具備下列權限:

  • 如何建立服務帳戶: iam.serviceAccountCreator 角色中的所有權限
  • 如要將權限授予服務帳戶,請執行下列操作: resourcemanager.projectIamAdmin 角色中的所有權限
  • 如要建立 VM,請按照下列步驟操作:
    • 專案的 compute.instances.create 權限
    • 如何使用自訂映像檔在映像檔上建立 VM: compute.images.useReadOnly
    • 如何使用快照建立 VM: 在快照上執行 compute.snapshots.useReadOnly
    • 如何使用執行個體範本在執行個體範本上建立 VM: compute.instanceTemplates.useReadOnly
    • 如要將舊版網路指派給專案中的 VM: compute.networks.use
    • 如要為專案中的 VM 指定靜態 IP 位址:compute.addresses.use
    • 如要在使用舊版網路時將外部 IP 位址指派給 VM,請在專案中使用 compute.networks.useExternalIp
    • 如要為 VM 指定子網路,請在專案或所選子網路中使用 compute.subnetworks.use
    • 如要在使用虛擬私有雲網路時將外部 IP 位址指派給 VM,請在專案或所選子網路上設定 compute.subnetworks.useExternalIp
    • 如何為專案中的 VM: compute.instances.setMetadata 設定 VM 執行個體中繼資料
    • 如何為 VM 設定標記:compute.instances.setTags
    • 如何為 VM 設定標籤:compute.instances.setLabels
    • 如何設定 VM 要使用的服務帳戶: 在 VM 上使用 compute.instances.setServiceAccount
    • 如要為專案中的 VM compute.disks.create 建立新磁碟
    • 如要以唯讀或讀寫模式連接現有磁碟:磁碟的 compute.disks.use
    • 如要以唯讀模式連接現有磁碟:磁碟上的 compute.disks.useReadOnly

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

總覽

建議您為 VM 設定服務帳戶,如下所示:

  1. 建立新的使用者管理服務帳戶,而不使用 Compute Engine 預設服務帳戶,並為該服務帳戶授予 IAM 角色,只針對該帳戶需要的資源和作業授予相關角色。
  2. 將服務帳戶附加至 VM。
  3. 在 VM 上設定雲端平台 (https://www.googleapis.com/auth/cloud-platform) 範圍。這可讓 VM 的服務帳戶呼叫具有使用權限的 Google Cloud API。
    • 如果您使用 Google Cloud 控制台指定服務帳戶,VM 的存取權範圍會自動預設為 cloud-platform 範圍。
    • 如果您使用 Google Cloud CLI 或 Compute Engine API 指定服務帳戶,可以使用 scopes 參數設定存取範圍。

設定服務帳戶

建立服務帳戶並指派必要的 IAM 角色。視需要指派多或少的 IAM 角色。您可以視需要修改服務帳戶的 IAM 角色。

Google 建議您限制服務帳戶的權限,並定期檢查服務帳戶權限,確保權限保持最新狀態。

請使用下列其中一種方法設定服務帳戶。

主控台

    In the Google Cloud console, go to the Create service account page.

    Go to Create service account
  1. Select your project.
  2. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

    In the Service account description field, enter a description. For example, Service account for quickstart.

  3. Click Create and continue.
  4. Grant the required roles to the service account.

    To grant a role, find the Select a role list, then select the role.

    To grant additional roles, click Add another role and add each additional role.

  5. Click Continue.
  6. In the Service 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.

  7. Click Done to finish creating the service account.

gcloud

    Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. To provide access to your project and your resources, grant a role to the service account:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
      • ROLE: the role to grant
    3. To grant another role to the service account, run the command as you did in the previous step.
    4. Grant the required role to the principal that will attach the service account to other resources.

      gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com --member="user:USER_EMAIL" --role=roles/iam.serviceAccountUser

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
      • USER_EMAIL: the email address for a Google Account

Terraform

如要建立服務帳戶,您可以使用 google_service_account 資源

resource "google_service_account" "default" {
  account_id   = "service-account-id"
  display_name = "Service Account"
}

請記得將 account_iddisplay_name 屬性的預留位置值替換為實際值。

如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 Terraform 指令」。

建立 VM 並附加服務帳戶

建立服務帳戶後,請建立 VM,並附加您在上一個章節中建立的服務帳戶。並將 VM 的存取範圍設為 cloud-platform

如果您已有現有的 VM,且想要設定該 VM 使用不同的服務帳戶,請參閱「變更已附加的服務帳戶」。

請使用下列其中一種方法建立 VM 並附加服務帳戶。

主控台

  1. 前往 Google Cloud 控制台的「Create an instance」(建立執行個體) 頁面。

    前往「Create an instance」(建立執行個體)

  2. 如要附加服務帳戶,請按照下列步驟操作:

    1. 按一下導覽選單中的「Security」(安全性)
    2. 在「Service account」清單中,選取您建立的服務帳戶。
    3. 在「存取權範圍」部分,選取「允許所有 Cloud API 的完整存取權」
  3. 選用:指定其他設定選項。詳情請參閱「建立執行個體時的設定選項」。

  4. 如要建立並啟動執行個體,請按一下「建立」

gcloud

如要使用 Google Cloud CLI 建立新的 VM 執行個體,並將其設為使用自訂服務帳戶,請使用 gcloud compute instances create 指令,並將服務帳戶電子郵件和 cloud-platform 存取權範圍提供給 VM 執行個體。

gcloud compute instances create VM_NAME \
    --service-account=SERVICE_ACCOUNT_EMAIL \
    --scopes=https://www.googleapis.com/auth/cloud-platform

更改下列內容:

  • SERVICE_ACCOUNT_EMAIL:您建立的服務帳戶電子郵件地址。例如:my-sa-123@my-project-123.iam.gserviceaccount.com。如要查看電子郵件地址,請參閱「列出服務帳戶」一文。
  • VM_NAME:VM 執行個體的名稱。

例如:

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

您也可以使用別名 --scopes=cloud-platform 指定範圍。這些別名只能由 gcloud CLI 識別。API 和其他程式庫無法辨識這些別名,因此您必須指定完整的範圍 URI。

Terraform

如要設定新的 VM 以使用服務帳戶,您可以使用 google_compute_instance 資源

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

使用 instances.insert 方法建立 VM,並指定 VM 執行個體的服務帳戶電子郵件和存取權範圍。

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

更改下列內容:

  • PROJECT_ID:要建立 VM 的專案 ID
  • ZONE:建立 VM 的可用區
  • MACHINE_TYPE_ZONE:包含要用於新 VM 的機器類型
  • MACHINE_TYPE:新 VM 的機器類型,可為預先定義自訂
  • VM_NAME:新 VM 的名稱
  • IMAGE_PROJECT:包含圖片的專案
    例如,如果您將 debian-10 指定為圖片系列,請將 debian-cloud 指定為圖片專案。
  • IMAGE:請指定下列任一值:
    • IMAGE:公開映像檔的特定版本

      例如: "sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200309"

    • IMAGE_FAMILY圖片系列

      這會根據最新的非淘汰作業系統映像檔建立 VM。舉例來說,如果您指定 "sourceImage": "projects/debian-cloud/global/images/family/debian-10",Compute Engine 會使用 Debian 10 映像檔系列中的最新 OS 映像檔建立 VM。

  • NETWORK_NAME:您要用於 VM 的 VPC 網路。您可以指定 default 來使用預設網路。
  • SERVICE_ACCOUNT_EMAIL:您建立的服務帳戶電子郵件地址。例如:my-sa-123@my-project-123.iam.gserviceaccount.com。如要查看電子郵件地址,請參閱「取得服務帳戶電子郵件」。
  • ENABLE_SECURE_BOOT:選用:如果您選擇支援受防護 VM 功能的映像檔,Compute Engine 預設會啟用虛擬信任平台模組 (vTPM)完整性監控。Compute Engine 預設不會啟用安全啟動

    如果您為 enableSecureBoot 指定 true,Compute Engine 會建立 VM,並啟用所有三種受防護的 VM 功能。在 Compute Engine 啟動 VM 後,您必須停止 VM,才能修改受防護的 VM 選項。

存取及使用其他 Google Cloud 服務

設定 VM 以使用服務帳戶後,應用程式就能使用服務帳戶進行驗證。最常見的方法是使用應用程式預設憑證和用戶端程式庫進行驗證。部分 Google Cloud 工具 (例如 gcloud CLI) 可自動使用服務帳戶,從 VM 存取 API。 Google Cloud 詳情請參閱「使用服務帳戶驗證工作負載」。

如果刪除服務帳戶,應用程式就無法再透過該服務帳戶存取Google Cloud 資源。如果您刪除了預設的 App Engine 和 Compute Engine 服務帳戶,VM 將無法再存取專案中的資源。如果您不確定是否會使用服務帳戶,Google 建議您在刪除之前先停用服務帳戶。如果仍需要停用的服務帳戶,可以重新啟用。

範例:從 VM 存取 Cloud Storage 資源

將 VM 設定為使用具有 storage.admin 角色的服務帳戶後,您就可以使用 gcloud CLI 等工具來管理儲存在 Cloud Storage 中的檔案。如要存取 Cloud Storage 資源,請完成下列步驟:

  1. 請確認已附加至 VM 的服務帳戶具有 roles/storage.admin 角色。

  2. 如果您的 VM 使用自訂 OS 映像檔,請安裝 gcloud CLI。根據預設,gcloud CLI 會安裝在 Google Cloud提供的大多數公開 OS 映像檔中。

  3. 連線至 VM。

  4. 在 VM 中使用 Google Cloud CLI 管理 Cloud Storage 資源。

後續步驟