צירוף דיסק אזורי למכונה וירטואלית ב-Compute Engine במצב קריאה-בלבד

חיבור דיסק אזורי למכונה וירטואלית של Compute Engine במצב קריאה וכתיבה חיבור דיסק אזורי למכונה וירטואלית אחת שפועלת ב-Google Compute Engine. כדי להשתמש בדיסק, צריך גם לטעון אותו באמצעות מערכת ההפעלה. הדיסק מצורף במצב קריאה בלבד. אפשר לחבר את הדיסק לכמה מכונות וירטואליות בו-זמנית.

דוגמת קוד

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Go במדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Go API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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 .