צירוף דיסק אזורי למכונה וירטואלית ב-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 .