Attach a regional disk to a Compute Engine VM instance in read-only mode

Attach a regional disk to a Compute Engine VM instance in read-write mode Attach a regional disk to a single virtual machine running in Google Compute Engine. The disk also needs to be mounted by the operating system before it can be used. The disk is attached in read-only mode. The disk can be attached to multiple VM instances simultaneously.

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Go API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.