Creare pianificazioni per gli snapshot dei dischi


Puoi creare una pianificazione di snapshot per eseguire regolarmente e automaticamente il backup dei dischi permanenti a livello di zona e di regione e degli Hyperdisk di Google Cloud. Utilizza le pianificazioni degli snapshot come best practice per eseguire il backup dei carichi di lavoro Compute Engine.

Se vuoi creare una pianificazione degli snapshot che acquisisca lo stato dei dati dell'applicazione al momento del backup, noto anche come snapshot coerente con l'applicazione, svuotamento dell'ambiente guest o snapshot VSS, consulta Creare snapshot dei dischi coerenti con l'applicazione Linux o Creare uno snapshot del disco coerente con l'applicazione Windows.

Per saperne di più sulle proprietà della pianificazione degli snapshot, consulta Proprietà della pianificazione degli snapshot.

Prima di iniziare

  • Consulta la sezione Limitazioni per le pianificazioni degli snapshot.
  • Se non l'hai ancora fatto, configura l'autenticazione. L'autenticazione è il processo mediante il quale la tua identità viene verificata per l'accesso a servizi e API. Google Cloud Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi autenticarti su Compute Engine selezionando una delle seguenti opzioni:

    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.
    3. Vai

      Per utilizzare gli Go esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      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.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      Java

      Per utilizzare gli Java esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      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.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      Node.js

      Per utilizzare gli Node.js esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      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.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      Python

      Per utilizzare gli Python esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza l'interfaccia a riga di comando gcloud, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.

      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.

      Per ulteriori informazioni, consulta Set up authentication for a local development environment.

      REST

      Per utilizzare gli esempi dell'API REST in questa pagina in un ambiente di sviluppo locale, utilizza le credenziali fornite a 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.

      Per ulteriori informazioni, consulta Eseguire l'autenticazione per l'utilizzo di REST nella documentazione Google Cloud sull'autenticazione.

Ruoli e autorizzazioni richiesti

Per ottenere le autorizzazioni necessarie per creare una pianificazione degli snapshot, chiedi all'amministratore di concederti i seguenti ruoli IAM nel progetto:

Per ulteriori informazioni sulla concessione dei ruoli, consulta Gestire l'accesso a progetti, cartelle e organizzazioni.

Questi ruoli predefiniti contengono le autorizzazioni necessarie per creare una pianificazione snapshot. Per visualizzare le autorizzazioni esatte richieste, espandi la sezione Autorizzazioni richieste:

Autorizzazioni obbligatorie

Per creare una pianificazione snapshot sono necessarie le seguenti autorizzazioni:

  • Per creare una pianificazione snapshot: compute.resourcePolicies.create nel progetto o nell'organizzazione
  • Per collegare una pianificazione degli snapshot a un disco:
    • compute.disks.addResourcePolicies sul disco
    • compute.resourcePolicies.use nel criterio delle risorse
  • Per creare un disco con una pianificazione snapshot:
    • compute.disks.create sul progetto
    • compute.resourcePolicies.create sul progetto
    • compute.disks.addResourcePolicies sul disco

Potresti anche ottenere queste autorizzazioni con ruoli personalizzati o altri ruoli predefiniti.

Panoramica della creazione di pianificazioni snapshot

Quando crei una pianificazione degli snapshot, crei un criterio di risorse che puoi applicare a uno o più volumi Hyperdisk o Disco permanente.

Puoi creare pianificazioni degli snapshot nei seguenti modi:

Utilizzo della crittografia con le pianificazioni degli snapshot

Se un disco utilizza una chiave di crittografia gestita dal cliente (CMEK), quando utilizzi una pianificazione degli snapshot per creare snapshot del disco, tutti gli snapshot creati vengono criptati automaticamente con la stessa chiave.

Non puoi utilizzare le pianificazioni degli snapshot con i dischi che utilizzano una chiave di crittografia fornita dal cliente (CSEK).

Crea pianificazione snapshot

Puoi creare una pianificazione degli snapshot per i tuoi dischi utilizzando la console Google Cloud, Google Cloud CLI o REST. Devi creare la pianificazione delle istantanee nella stessa regione in cui si trova il disco. Ad esempio, se il tuo disco si trova nella zona us-west1-a, devi creare la pianificazione degli snapshot nella regione us-west1. Tuttavia, puoi scegliere di archiviare gli snapshot generati dalla pianificazione degli snapshot in una posizione diversa.

Console

  1. Nella console Google Cloud, vai alla pagina Istanze VM.

    Vai a Istanze VM
    I passaggi rimanenti verranno visualizzati automaticamente nella console Google Cloud.

  2. Seleziona il progetto che contiene le istanze VM.
  3. Nella colonna Nome, fai clic sul nome della VM con il disco permanente per cui vuoi creare la pianificazione di snapshot.
  4. In Spazio di archiviazione, fai clic sul nome del disco di avvio o del disco aggiuntivo per cui vuoi creare la pianificazione di snapshot.
  5. Fai clic su Modifica. Potresti dover fare clic sul menu Altre azioni e poi su Modifica.
  6. In Pianificazione di snapshot, scegli Crea una pianificazione.
  7. In Nome, inserisci uno dei seguenti nomi per la pianificazione di snapshot:
    • boot-disk-snapshot-schedule
    • attached-persistent-disk-snapshot-schedule
  8. Nella sezione Località, scegli la località di archiviazione degli snapshot. La località predefinita personalizzata o predefinita definita nelle impostazioni degli snapshot viene selezionata automaticamente. Se vuoi, puoi ignorare le impostazioni degli snapshot e archiviare gli snapshot in una località di archiviazione personalizzata nel seguente modo:

    1. Scegli il tipo di località di archiviazione che preferisci per lo snapshot.

      • Scegli Più regioni per una maggiore disponibilità a un costo superiore.
      • Scegli gli snapshot regionali per un maggiore controllo sulla località fisica dei dati a un costo inferiore.
    2. Nel campo Seleziona località, seleziona la regione specifica o più regioni che vuoi utilizzare. Per utilizzare la regione o più regioni più vicine al tuo disco di origine, seleziona Basata sulla posizione del disco.

  9. Per completare la creazione della pianificazione di snapshot, fai clic su Crea.
  10. Per collegare questa pianificazione di snapshot al disco permanente, fai clic su Salva.

gcloud

  • Per pianificare snapshot a livello globale per un disco, utilizza il comando gcloud compute resource-policies create snapshot-schedule. Imposta la frequenza della programmazione su oraria, giornaliera o settimanale.

    gcloud compute resource-policies create snapshot-schedule SCHEDULE_NAME \
        --description "SCHEDULE_DESCRIPTION" \
        --max-retention-days MAX_RETENTION_DAYS \
        --start-time START_TIME \
        --hourly-schedule SNAPSHOT_INTERVAL \
        --daily-schedule \
        --weekly-schedule SNAPSHOT_INTERVAL or --weekly-schedule-from-file FILE_NAME \
        --on-source-disk-delete DELETION_OPTION \
        --storage-location=STORAGE_LOCATION
    
  • (Anteprima) Per pianificare snapshot con ambito regionale per un disco, utilizza il comando gcloud compute resource-policies create snapshot-schedule e specifica la regione di snapshot.

    gcloud beta compute resource-policies create snapshot-schedule SCHEDULE_NAME \
        --description "SCHEDULE_DESCRIPTION" \
        --max-retention-days MAX_RETENTION_DAYS \
        --start-time START_TIME \
        --hourly-schedule SNAPSHOT_INTERVAL \
        --daily-schedule \
        --weekly-schedule SNAPSHOT_INTERVAL or --weekly-schedule-from-file FILE_NAME \
        --on-source-disk-delete DELETION_OPTION \
        --storage-location=STORAGE_LOCATION \
        --region REGION \
        --snapshot-region SNAPSHOT_REGION
    

Sostituisci quanto segue:

  • SCHEDULE_NAME: il nome della pianificazione degli snapshot.
  • SCHEDULE_DESCRIPTION: una descrizione della programmazione degli snapshot. Racchiudi la descrizione tra virgolette.
  • REGION: la posizione del criterio della risorsa per la pianificazione degli snapshot.
  • SNAPSHOT_REGION: la regione a cui è associato lo snapshot pianificato.
  • MAX_RETENTION_DAYS: il numero di giorni per conservare lo snapshot.

    Ad esempio, un valore 3 indica che gli snapshot vengono conservati per 3 giorni prima di essere eliminati. Devi utilizzare un valore pari o superiore a 1.

  • START_TIME: l'ora di inizio nel fuso orario UTC. L'ora deve iniziare a ora in punto.

    Ad esempio:

    • Le 14:00 PST devono essere specificate come 22:00.
    • Se imposti un'ora di inizio pari a 22:13, viene visualizzato un errore.

    Se utilizzi il flag --weekly-schedule-from-file e specifichi un'ora di inizio all'interno del file, non è necessario includere questo flag.

  • SNAPSHOT_INTERVAL: l'intervallo tra la creazione di snapshot successivi. Gli indicatori della frequenza degli snapshot hourly-schedule, daily-schedule, weekly-schedule e weekly-schedule-from-file sono esclusivi l'uno dell'altro. Puoi utilizzarne solo uno per la pianificazione degli snapshot.

    • Imposta un programma giornaliero includendo il flag --daily-schedule senza alcun valore.
    • Imposta una pianificazione ogni ora con il flag --hourly-schedule impostato su un valore intero compreso tra 1 e 23. Per generare snapshot alla stessa ora ogni giorno, scegli un numero di ore diviso uniformemente in 24. Ad esempio, se imposti --hourly-schedule su 12, viene creato un snapshot ogni 12 ore.
    • Imposta una pianificazione settimanale con il flag --weekly-schedule impostato sulgiorno della settimana in cui vuoi che venga creato lo snapshot. Devi scrivere per esteso il giorno della settimana; i valori non sono sensibili alle maiuscole. Ad esempio, per eseguire il backup del disco ogni venerdì, il comando includerà --weekly-schedule=friday.
    • Imposta una programmazione settimanale avanzata, specificando giorni diversi della settimana e orari di inizio diversi, includendo il flag --weekly-schedule-from-file. Sostituisci FILE_NAME con il nome del file che contiene la pianificazione degli snapshot settimanali. Sebbene sia possibile specificare giorni diversi della settimana e orari di inizio diversi utilizzando un file, non è possibile specificare più pianificazioni settimanali direttamente sulla riga di comando. Ad esempio, il tuo file potrebbe specificare due pianificazioni settimanali, il lunedì e il mercoledì, ma non puoi duplicare questa impostazione sulla riga di comando:

      [
        {"day": "MONDAY", "startTime": "04:00"},
        {"day": "WEDNESDAY", "startTime": "02:00"}
      ]
      

      Se includi un'ora di inizio nel file, non è necessario impostare il --start-time flag sulla riga di comando. La pianificazione utilizza il fuso orario UTC.

  • DELETION_OPTION: determina cosa succede ai tuoi snapshot se il disco di origine viene eliminato. Se vuoi conservare tutti gli snapshot generati, puoi omettere questo flag. In caso contrario, specifica apply-retention-policy per utilizzare le impostazioni in un criterio di conservazione.

  • STORAGE_LOCATION: facoltativo, la posizione di archiviazione. Se ometti questo flag, viene utilizzata la posizione di archiviazione predefinita.

Esempi

In tutti i seguenti esempi:

  • La regola di eliminazione del disco è inclusa; il flag --on-source-disk-delete è impostato sul valore predefinito keep-auto-snapshots per conservare definitivamente tutti gli snapshot generati automaticamente. In alternativa, imposta questo flag su apply-retention-policy per utilizzare i criteri di conservazione degli snapshot.
  • La posizione di archiviazione è impostata manualmente su US, pertanto tutte le istantanee generate vengono archiviate nella multi-regione degli Stati Uniti.
  • Le etichette env=dev e media=images vengono applicate a tutti gli screenshot generati.
  • Il criterio di conservazione è impostato su 10 giorni.

Pianificazione oraria:in questo esempio, la pianificazione degli snapshot inizia alle 22:00 UTC (14:00 PST) e viene eseguita ogni 4 ore.

  gcloud compute resource-policies create snapshot-schedule hourly-schedule1 \
      --description "MY HOURLY SNAPSHOT SCHEDULE" \
      --max-retention-days 10 \
      --start-time 22:00 \
      --hourly-schedule 4 \
      --region us-west1 \
      --on-source-disk-delete keep-auto-snapshots \
      --snapshot-labels env=dev,media=images \
      --storage-location US

Pianificazione giornaliera: in questo esempio, la pianificazione degli istantanei inizia alle 22:00 UTC (14:00 PST) e viene eseguita ogni giorno alla stessa ora. Il flag --daily-schedule deve essere presente, ma senza un valore associato.

gcloud compute resource-policies create snapshot-schedule daily-schedule2 \
    --description "MY DAILY SNAPSHOT SCHEDULE" \
    --max-retention-days 10 \
    --start-time 22:00 \
    --daily-schedule \
    --region us-west1 \
    --on-source-disk-delete keep-auto-snapshots \
    --snapshot-labels env=dev,media=images \
    --storage-location US

Pianificazione settimanale: in questo esempio, la pianificazione degli istantanei inizia alle 22:00 UTC (14:00 PST) e viene eseguita ogni settimana di martedì.

gcloud compute resource-policies create snapshot-schedule weekly-schedule3 \
    --description "MY WEEKLY SNAPSHOT SCHEDULE" \
    --max-retention-days 10 \
    --start-time 22:00 \
    --weekly-schedule tuesday \
    --region us-west1 \
    --on-source-disk-delete keep-auto-snapshots \
    --snapshot-labels env=dev,media=images \
    --storage-location US

Vai

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// createSnapshotSchedule creates a snapshot schedule.
func createSnapshotSchedule(w io.Writer, projectID, scheduleName, region string) error {
	// projectID := "your_project_id"
	// snapshotName := "your_snapshot_name"
	// region := "eupore-central2"

	ctx := context.Background()

	snapshotsClient, err := compute.NewResourcePoliciesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewResourcePoliciesRESTClient: %w", err)
	}
	defer snapshotsClient.Close()

	req := &computepb.InsertResourcePolicyRequest{
		Project: projectID,
		Region:  region,
		ResourcePolicyResource: &computepb.ResourcePolicy{
			Name:        proto.String(scheduleName),
			Description: proto.String("MY DAILY SNAPSHOT SCHEDULE"),
			Region:      proto.String("europe-central2"),
			SnapshotSchedulePolicy: &computepb.ResourcePolicySnapshotSchedulePolicy{
				RetentionPolicy: &computepb.ResourcePolicySnapshotSchedulePolicyRetentionPolicy{
					MaxRetentionDays: proto.Int32(10),
					// Check the OnSourceDiskDelete enum for the list of possible values.
					OnSourceDiskDelete: proto.String("KEEP_AUTO_SNAPSHOTS"),
				},
				Schedule: &computepb.ResourcePolicySnapshotSchedulePolicySchedule{
					DailySchedule: &computepb.ResourcePolicyDailyCycle{
						DaysInCycle: proto.Int32(1),
						StartTime:   proto.String("22:00"),
					},
				},
				SnapshotProperties: &computepb.ResourcePolicySnapshotSchedulePolicySnapshotProperties{
					StorageLocations: []string{"eu"},
					Labels: map[string]string{
						"env":   "dev",
						"media": "images",
					},
				},
			},
		},
	}
	op, err := snapshotsClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create snapshot schedule: %w", err)
	}

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

	fmt.Fprint(w, "Snapshot schedule created\n")

	return nil
}

Java

import com.google.cloud.compute.v1.InsertResourcePolicyRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import com.google.cloud.compute.v1.ResourcePolicy;
import com.google.cloud.compute.v1.ResourcePolicyHourlyCycle;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicy;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy.OnSourceDiskDelete;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySchedule;
import com.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySnapshotProperties;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSnapshotSchedule {
  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region in which you want to create the snapshot schedule.
    String region = "us-central1";
    // Name of the snapshot schedule you want to create.
    String snapshotScheduleName = "YOUR_SCHEDULE_NAME";
    // Description of the snapshot schedule.
    String scheduleDescription = "YOUR_SCHEDULE_DESCRIPTION";
    // Maximum number of days to retain snapshots.
    int maxRetentionDays = 10;
    // Storage location for the snapshots.
    // More about storage locations:
    // https://cloud.google.com/compute/docs/disks/snapshots?authuser=0#selecting_a_storage_location
    String storageLocation = "US";

    createSnapshotSchedule(projectId, region, snapshotScheduleName, scheduleDescription,
            maxRetentionDays, storageLocation);
  }

  // Creates a snapshot schedule policy.
  public static Status createSnapshotSchedule(String projectId, String region,
            String snapshotScheduleName, String scheduleDescription, int maxRetentionDays,
            String storageLocation)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
      int snapshotInterval = 10; // Create a snapshot every 10 hours
      String startTime = "08:00"; // Define the hourly schedule

      ResourcePolicyHourlyCycle hourlyCycle = ResourcePolicyHourlyCycle.newBuilder()
              .setHoursInCycle(snapshotInterval)
              .setStartTime(startTime)
              .build();

      ResourcePolicySnapshotSchedulePolicyRetentionPolicy retentionPolicy =
              ResourcePolicySnapshotSchedulePolicyRetentionPolicy.newBuilder()
                      .setMaxRetentionDays(maxRetentionDays)
                      .setOnSourceDiskDelete(OnSourceDiskDelete.KEEP_AUTO_SNAPSHOTS.toString())
              .build();

      ResourcePolicySnapshotSchedulePolicySnapshotProperties snapshotProperties =
              ResourcePolicySnapshotSchedulePolicySnapshotProperties.newBuilder()
                      .addStorageLocations(storageLocation)
                      .build();

      ResourcePolicySnapshotSchedulePolicy snapshotSchedulePolicy =
              ResourcePolicySnapshotSchedulePolicy.newBuilder()
                      .setRetentionPolicy(retentionPolicy)
                      .setSchedule(ResourcePolicySnapshotSchedulePolicySchedule.newBuilder()
                               .setHourlySchedule(hourlyCycle)
                               .build())
                      .setSnapshotProperties(snapshotProperties)
                      .build();

      ResourcePolicy resourcePolicy = ResourcePolicy.newBuilder()
              .setName(snapshotScheduleName)
              .setDescription(scheduleDescription)
              .setSnapshotSchedulePolicy(snapshotSchedulePolicy)
              .build();
      InsertResourcePolicyRequest request = InsertResourcePolicyRequest.newBuilder()
              .setProject(projectId)
              .setRegion(region)
              .setResourcePolicyResource(resourcePolicy)
              .build();

      Operation response = resourcePoliciesClient.insertAsync(request)
              .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        throw new Error("Snapshot schedule creation failed! " + response.getError());
      }
      return response.getStatus();
    }
  }
}

Node.js

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// Instantiate a resourcePoliciesClient
const resourcePoliciesClient = new computeLib.ResourcePoliciesClient();
// Instantiate a regionOperationsClient
const regionOperationsClient = new computeLib.RegionOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The project name.
const projectId = await resourcePoliciesClient.getProjectId();

// The location of the snapshot schedule resource policy.
// region = 'us-central1';

// The name of the snapshot schedule.
// snapshotScheduleName = 'snapshot-schedule-name';

// The description of the snapshot schedule.
const snapshotScheduleDescription = 'snapshot schedule description...';

async function callCreateSnapshotSchedule() {
  const [response] = await resourcePoliciesClient.insert({
    project: projectId,
    region,
    resourcePolicyResource: new compute.ResourcePolicy({
      name: snapshotScheduleName,
      description: snapshotScheduleDescription,
      snapshotSchedulePolicy:
        new compute.ResourcePolicyInstanceSchedulePolicySchedule({
          retentionPolicy:
            new compute.ResourcePolicySnapshotSchedulePolicyRetentionPolicy({
              maxRetentionDays: 5,
            }),
          schedule: new compute.ResourcePolicySnapshotSchedulePolicySchedule({
            // Similarly, you can create a weekly or monthly schedule.
            // Review the resourcePolicies.insert method for details specific to setting a weekly or monthly schedule.
            // To see more details, open: `https://cloud.google.com/compute/docs/disks/scheduled-snapshots?authuser=0#create_snapshot_schedule`
            dailySchedule: new compute.ResourcePolicyDailyCycle({
              startTime: '12:00',
              daysInCycle: 1,
            }),
          }),
          snapshotProperties:
            new compute.ResourcePolicySnapshotSchedulePolicySnapshotProperties(
              {
                guestFlush: false,
                labels: {
                  env: 'dev',
                  media: 'images',
                },
                // OPTIONAL: the storage location. If you omit this flag, the default storage location is used.
                // storageLocations: 'storage-location',
              }
            ),
        }),
    }),
  });

  let operation = response.latestResponse;

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await regionOperationsClient.wait({
      operation: operation.name,
      project: projectId,
      region,
    });
  }

  console.log(`Snapshot schedule: ${snapshotScheduleName} created.`);
}

await callCreateSnapshotSchedule();

Python

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def snapshot_schedule_create(
    project_id: str,
    region: str,
    schedule_name: str,
    schedule_description: str,
    labels: dict,
) -> compute_v1.ResourcePolicy:
    """
    Creates a snapshot schedule for disks for a specified project and region.
    Args:
        project_id (str): The ID of the Google Cloud project.
        region (str): The region where the snapshot schedule will be created.
        schedule_name (str): The name of the snapshot schedule group.
        schedule_description (str): The description of the snapshot schedule group.
        labels (dict): The labels to apply to the snapshots. Example: {"env": "dev", "media": "images"}
    Returns:
        compute_v1.ResourcePolicy: The created resource policy.
    """

    # # Every hour, starts at 12:00 AM
    # hourly_schedule = compute_v1.ResourcePolicyHourlyCycle(
    #     hours_in_cycle=1, start_time="00:00"
    # )
    #
    # # Every Monday, starts between 12:00 AM and 1:00 AM
    # day = compute_v1.ResourcePolicyWeeklyCycleDayOfWeek(
    #     day="MONDAY", start_time="00:00"
    # )
    # weekly_schedule = compute_v1.ResourcePolicyWeeklyCycle(day_of_weeks=[day])

    # In this example we use daily_schedule - every day, starts between 12:00 AM and 1:00 AM
    daily_schedule = compute_v1.ResourcePolicyDailyCycle(
        days_in_cycle=1, start_time="00:00"
    )

    schedule = compute_v1.ResourcePolicySnapshotSchedulePolicySchedule()
    # You can change the schedule type to daily_schedule, weekly_schedule, or hourly_schedule
    schedule.daily_schedule = daily_schedule

    # Autodelete snapshots after 5 days
    retention_policy = compute_v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy(
        max_retention_days=5
    )
    snapshot_properties = (
        compute_v1.ResourcePolicySnapshotSchedulePolicySnapshotProperties(
            guest_flush=False, labels=labels
        )
    )

    snapshot_policy = compute_v1.ResourcePolicySnapshotSchedulePolicy()
    snapshot_policy.schedule = schedule
    snapshot_policy.retention_policy = retention_policy
    snapshot_policy.snapshot_properties = snapshot_properties

    resource_policy_resource = compute_v1.ResourcePolicy(
        name=schedule_name,
        description=schedule_description,
        snapshot_schedule_policy=snapshot_policy,
    )

    client = compute_v1.ResourcePoliciesClient()
    operation = client.insert(
        project=project_id,
        region=region,
        resource_policy_resource=resource_policy_resource,
    )
    wait_for_extended_operation(operation, "Resource Policy creation")

    return client.get(project=project_id, region=region, resource_policy=schedule_name)

REST

  • Per creare una pianificazione degli snapshot per gli snapshot a livello globale, crea una richiesta POST a resourcePolicies.insert. Devi includere il nome della pianificazione degli snapshot e la relativa frequenza.

    Puoi anche specificare manualmente una posizione di archiviazione degli snapshot e aggiungere etichette delle risorse nella richiesta.

    Per impostazione predefinita, il parametro onSourceDiskDelete è impostato su keepAutoSnapshots. Ciò significa che se il disco di origine viene eliminato, lo snapshot generato automaticamente per quel disco viene conservato a tempo indeterminato. In alternativa, puoi impostare il flag su applyRetentionPolicy per applicare il criterio di conservazione.

    Nell'esempio seguente viene impostata una pianificazione giornaliera degli snapshot che inizia alle 12:00 UTC (04:00 PST) e si ripete ogni giorno. L'esempio imposta anche un criterio di conservazione di 5 giorni; dopo 5 giorni, gli snapshot vengono rimossi automaticamente.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies
    
        {
        "name": "SCHEDULE_NAME",
        "description": "SCHEDULE_DESCRIPTION",
        "snapshotSchedulePolicy": {
          "schedule": {
            "dailySchedule": {
              "startTime": "12:00",
              "daysInCycle": "1"
            }
          },
          "retentionPolicy": {
            "maxRetentionDays": "5"
          },
          "snapshotProperties": {
            "guestFlush": "False",
            "labels": {
              "env": "dev",
              "media": "images"
            },
            "storageLocations": "STORAGE_LOCATION"
          }
        }
        }
    
  • (Anteprima) Per creare una pianificazione degli snapshot per gli snapshot a livello di regione, crea una richiesta POST a resourcePolicies.insert e specifica la regione di snapshot.

    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/regions/REGION/resourcePolicies
    
        {
        "name": "SCHEDULE_NAME",
        "description": "SCHEDULE_DESCRIPTION",
        "snapshotSchedulePolicy": {
          "schedule": {
            "dailySchedule": {
              "startTime": "12:00",
              "daysInCycle": "1"
            }
          },
          "retentionPolicy": {
            "maxRetentionDays": "5"
          },
          "snapshotProperties": {
            "guestFlush": "False",
            "region": "SNAPSHOT_REGION"
          }
        }
        }
    

Sostituisci quanto segue:

  • PROJECT_ID: il nome del progetto
  • REGION: la posizione della policy della risorsa di pianificazione degli snapshot
  • SNAPSHOT_REGION: la regione a cui è associato lo scopo dello snapshot pianificato
  • SCHEDULE_DESCRIPTION: la descrizione della pianificazione degli snapshot
  • SCHEDULE_NAME: il nome della pianificazione di snapshot
  • STORAGE_LOCATION: facoltativo, la posizione di archiviazione. Se ometti questo flag, viene utilizzata la posizione di archiviazione predefinita.

Analogamente, puoi creare una pianificazione settimanale o mensile. Consulta il metodo resourcePolicies.insert per informazioni specifiche sull'impostazione di una pianificazione settimanale o mensile.

Ad esempio, la seguente richiesta crea una pianificazione settimanale che viene eseguita di martedì alle 09:00 UTC.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies

{
   "name": "SCHEDULE_NAME",
   "description": "SCHEDULE_DESCRIPTION",
   "snapshotSchedulePolicy": {
      "schedule": {
        "weeklySchedule": {
          "dayOfWeeks": [
          {
            "day": "Tuesday",
            "startTime": "9:00"
          }
          ]
        }
      },
      "retentionPolicy": {
          "maxRetentionDays": "5"
      },
      "snapshotProperties": {
          "guestFlush": "False",
          "labels": {
               "production": "webserver"
          },
          "storageLocations": "US"
      }
  }
}

Collegare una pianificazione di snapshot a un disco

Dopo aver creato una pianificazione, collegala a un disco esistente. Utilizza la console, gcloud CLI o l'API Compute Engine.

Console

Collega una pianificazione di snapshot a un disco esistente.

  1. Nella console Google Cloud, vai alla pagina Dischi.

    Vai a Dischi

  2. Seleziona il nome del disco a cui vuoi associare una pianificazione degli snapshot. Viene visualizzata la pagina Gestisci disco.

  3. Nella pagina Gestisci disco, fai clic su Modifica. Potrebbe essere necessario fare prima clic sul menu Altre azioni.

  4. Utilizza il menu a discesa Pianificazione istantanee per aggiungere la pianificazione al disco. In alternativa, crea una nuova programmazione.

  5. Se hai creato una nuova pianificazione, fai clic su Crea.

  6. Fai clic su Salva per completare l'attività.

gcloud

Per collegare una pianificazione degli snapshot a un disco, utilizza il comando gcloud disks add-resource-policies.

gcloud compute disks add-resource-policies DISK_NAME \
    --resource-policies SCHEDULE_NAME \
    --zone ZONE

Sostituisci quanto segue:

  • DISK_NAME: il nome del disco esistente
  • SCHEDULE_NAME: il nome della pianificazione di snapshot
  • ZONE: la posizione del disco

Vai

import (
	"context"
	"fmt"
	"io"

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

// attachSnapshotSchedule attaches a snapshot schedule to disk.
func attachSnapshotSchedule(w io.Writer, projectID, scheduleName, diskName, region string) error {
	// projectID := "your_project_id"
	// snapshotName := "your_snapshot_name"
	// diskName := "your_disk_name"
	// region := "europe-central2"

	ctx := context.Background()

	disksClient, err := compute.NewRegionDisksRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewDisksRESTClient: %w", err)
	}
	defer disksClient.Close()

	req := &computepb.AddResourcePoliciesRegionDiskRequest{
		Project: projectID,
		Region:  region,
		Disk:    diskName,
		RegionDisksAddResourcePoliciesRequestResource: &computepb.RegionDisksAddResourcePoliciesRequest{
			ResourcePolicies: []string{
				fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", projectID, region, scheduleName),
			},
		},
	}
	op, err := disksClient.AddResourcePolicies(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to attach schedule: %w", err)
	}

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

	fmt.Fprint(w, "Snapshot schedule attached\n")

	return nil
}

Java

import com.google.cloud.compute.v1.AddResourcePoliciesDiskRequest;
import com.google.cloud.compute.v1.DisksAddResourcePoliciesRequest;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AttachSnapshotScheduleToDisk {
  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the zone where your disk is located.
    String zone = "us-central1-a";
    // Name of the disk you want to attach the snapshot schedule to.
    String diskName = "YOUR_DISK_NAME";
    // Name of the snapshot schedule you want to attach.
    String snapshotScheduleName = "YOUR_SNAPSHOT_SCHEDULE_NAME";
    // Name of the region where your snapshot schedule is located.
    String region = "us-central1";

    attachSnapshotScheduleToDisk(projectId, zone, diskName, snapshotScheduleName, region);
  }

  // Attaches a snapshot schedule to a disk.
  public static Status attachSnapshotScheduleToDisk(
        String projectId, String zone, String diskName, String snapshotScheduleName, String region)
        throws IOException, ExecutionException, InterruptedException, TimeoutException {

    String resourcePolicyLink = String.format(
            "projects/%s/regions/%s/resourcePolicies/%s", projectId, region, snapshotScheduleName);
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (DisksClient disksClient = DisksClient.create()) {

      AddResourcePoliciesDiskRequest request = AddResourcePoliciesDiskRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setDisk(diskName)
              .setDisksAddResourcePoliciesRequestResource(
                      DisksAddResourcePoliciesRequest.newBuilder()
                              .addResourcePolicies(resourcePolicyLink)
                              .build())
              .build();

      Operation response = disksClient.addResourcePoliciesAsync(request).get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        throw new Error("Error attaching snapshot schedule to disk: " + response.getError());
      }
      return response.getStatus();
    }
  }
}

Python

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def snapshot_schedule_attach(
    project_id: str, zone: str, region: str, disk_name: str, schedule_name: str
) -> None:
    """
    Attaches a snapshot schedule to a specified disk.
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone where the disk is located.
        region (str): The region where the snapshot schedule was created
        disk_name (str): The name of the disk to which the snapshot schedule will be attached.
        schedule_name (str): The name of the snapshot schedule that you are applying to this disk
    Returns:
        None
    """
    disks_add_request = compute_v1.DisksAddResourcePoliciesRequest(
        resource_policies=[f"regions/{region}/resourcePolicies/{schedule_name}"]
    )

    client = compute_v1.DisksClient()
    operation = client.add_resource_policies(
        project=project_id,
        zone=zone,
        disk=disk_name,
        disks_add_resource_policies_request_resource=disks_add_request,
    )
    wait_for_extended_operation(operation, "Attaching snapshot schedule to disk")

REST

Crea una richiesta POST a disks.addResourcePolicies per collegare una pianificazione di snapshot a un disco esistente.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks/DISK_NAME/addResourcePolicies

{
  "resourcePolicies": [
    "regions/REGION/resourcePolicies/SCHEDULE_NAME"
  ]
}

Sostituisci quanto segue:

  • PROJECT_ID: il nome del progetto
  • ZONE: la zona in cui si trova il disco
  • REGION: la regione in cui è stata creata la pianificazione snapshot
  • DISK_NAME: il nome del disco
  • SCHEDULE_NAME: il nome della pianificazione degli snapshot che stai applicando a questo disco

Creare un disco con una pianificazione degli snapshot

Puoi utilizzare la console Google Cloud o gcloud CLI per creare contemporaneamente un disco e una pianificazione degli snapshot.

Console

  1. Nella console Google Cloud, vai alla pagina Dischi.

    Vai a Dischi

  2. Fai clic su Crea disco.

  3. Compila i campi obbligatori per creare un disco a livello di zona o di regione.

  4. Crea il disco nella stessa regione della pianificazione degli snapshot.

  5. Compila i campi per la pianificazione degli snapshot.

  6. Utilizza il menu a discesa e compila i campi per creare la pianificazione.

  7. Fai clic su Crea per creare la pianificazione.

  8. Fai clic su Crea per creare il disco.

gcloud

Utilizza il comando gcloud disks create per creare un disco permanente o un Hyperdisk a livello di zona o di regione e associa una pianificazione degli snapshot.

gcloud compute disks create DISK_NAME \
     --resource-policies SCHEDULE_NAME \
     --zone ZONE

Sostituisci quanto segue:

  • DISK_NAME: il nome del nuovo disco
  • SCHEDULE_NAME: il nome della pianificazione degli snapshot
  • ZONE: la posizione in cui crei il disco. Il disco deve trovarsi in una zona della stessa regione della pianificazione delle istantanee.

Vai

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// createDiskWithSnapshotSchedule creates a new empty regional disk with snapshot schedule
func createDiskWithSnapshotSchedule(
	w io.Writer,
	projectID, region, diskName, diskType, scheduleName string,
	replicaZones []string,
	diskSizeGb int64,
) error {
	// projectID := "your_project_id"
	// region := "us-west3" // should match diskType below
	// diskName := "your_disk_name"
	// diskType := "regions/us-west3/diskTypes/pd-ssd"
	// scheduleName := "your_schedule_name"
	// replicaZones := []string{"us-west3-a", "us-west3-b"}
	// diskSizeGb := 120

	// Exactly two replica zones must be specified
	replicaZoneURLs := []string{
		fmt.Sprintf("projects/%s/zones/%s", projectID, replicaZones[0]),
		fmt.Sprintf("projects/%s/zones/%s", projectID, replicaZones[1]),
	}

	ctx := context.Background()
	disksClient, err := compute.NewRegionDisksRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewRegionDisksRESTClient: %w", err)
	}
	defer disksClient.Close()

	req := &computepb.InsertRegionDiskRequest{
		Project: projectID,
		Region:  region,
		DiskResource: &computepb.Disk{
			Name:         proto.String(diskName),
			Region:       proto.String(region),
			Type:         proto.String(diskType),
			SizeGb:       proto.Int64(diskSizeGb),
			ReplicaZones: replicaZoneURLs,
			ResourcePolicies: []string{
				fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s", projectID, region, scheduleName),
			},
		},
	}

	op, err := disksClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create disk with schedule: %w", err)
	}

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

	fmt.Fprintf(w, "Disk with schedule created\n")

	return nil
}

Java

import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDiskWithSnapshotSchedule {
  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the zone in which you want to create the disk.
    String zone = "us-central1-a";
    // Name of the disk you want to create.
    String diskName = "YOUR_DISK_NAME";
    // Name of the schedule you want to link to the disk.
    String snapshotScheduleName = "YOUR_SCHEDULE_NAME";

    createDiskWithSnapshotSchedule(projectId, zone, diskName, snapshotScheduleName);
  }

  // Creates disk with linked snapshot schedule.
  public static Status createDiskWithSnapshotSchedule(
      String projectId, String zone, String diskName, String snapshotScheduleName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (DisksClient disksClient = DisksClient.create()) {
      String region = zone.substring(0, zone.lastIndexOf('-'));
      // Get the resource policy to link to the disk
      String resourcePolicyLink = String.format("projects/%s/regions/%s/resourcePolicies/%s",
              projectId, region, snapshotScheduleName);

      Disk disk = Disk.newBuilder()
              .setName(diskName)
              .setZone(zone)
              .addAllResourcePolicies(List.of(resourcePolicyLink))
              .build();

      Operation response = disksClient.insertAsync(projectId, zone, disk).get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        throw new Error("Disk creation failed! " + response.getError());
      }
      return response.getStatus();
    }
  }
}

Passaggi successivi