以唯讀模式將區域磁碟附加至 Compute Engine VM 執行個體

以讀寫模式將區域磁碟附加至 Compute Engine VM 執行個體 將區域磁碟附加至在 Google Compute Engine 中執行的單一虛擬機器。磁碟也必須由作業系統掛接,才能使用。 磁碟是以唯讀模式連接,磁碟可同時連接至多個 VM 執行個體。

程式碼範例

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 Compute Engine Go API 參考說明文件

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// Attaches the provided regional disk in read-only mode to the given VM.
// Read-only disks can be attached to multiple VMs at once.
func attachRegionalDiskReadOnly(w io.Writer, projectID, zone, instanceName, diskUrl string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a" // refers to the instance, not the disk
	// instanceName := "your_instance_name"
	// diskUrl := "projects/your_project/regions/europe-west3/disks/your_disk"

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return err
	}
	defer instancesClient.Close()

	mode := "READ_ONLY"

	req := &computepb.AttachDiskInstanceRequest{
		AttachedDiskResource: &computepb.AttachedDisk{
			Source: &diskUrl,
			Mode:   &mode,
		},
		Instance: instanceName,
		Project:  projectID,
		Zone:     zone,
	}

	op, err := instancesClient.AttachDisk(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to attach disk: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Disk attached\n")

	return nil
}

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器