Gestire le pianificazioni degli snapshot per i dischi


Questo documento descrive come gestire le pianificazioni snapshot per i volumi Persistent Disk e Google Cloud Hyperdisk a livello di zona e di regione.

Puoi gestire le pianificazioni degli snapshot nel seguente modo:

  • Visualizzare le pianificazioni degli snapshot
  • Modificare le pianificazioni degli snapshot
  • Elimina pianificazioni snapshot

Puoi anche configurare avvisi per gli snapshot pianificati.

Prima di iniziare

  • Se non l'hai ancora fatto, configura l'autenticazione. L'autenticazione è il processo mediante il quale la tua identità viene verificata per l'accesso ai Google Cloud servizi e alle API. 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 esempi di Go questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, 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, vedi Set up authentication for a local development environment.

        Java

        Per utilizzare gli esempi di Java questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, 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, vedi Set up authentication for a local development environment.

        Node.js

        Per utilizzare gli esempi di Node.js questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, 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, vedi Set up authentication for a local development environment.

        Python

        Per utilizzare gli esempi di Python questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, 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, vedi Set up authentication for a local development environment.

        REST

        Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, utilizzi le credenziali che fornisci 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 saperne di più, consulta la sezione Autenticarsi per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud .

Ruoli e autorizzazioni richiesti

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

Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Questi ruoli predefiniti contengono le autorizzazioni necessarie per creare una pianificazione di snapshot. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per creare una pianificazione di snapshot sono necessarie le seguenti autorizzazioni:

  • Per visualizzare le pianificazioni degli snapshot: compute.resourcePolicies.list sul progetto o sull'organizzazione
  • Per aggiornare una pianificazione snapshot:
    • compute.resourcePolicies.update sulla policy risorse
    • compute.resourcePolicies.get sulla policy risorse
  • Per sostituire una pianificazione di snapshot:
    • compute.resourcePolicies.use sulla policy risorse
    • compute.disks.addResourcePolicies sul disco
    • compute.disks.removeResourcePolicies sul disco
  • Per eliminare una pianificazione snapshot:
    • compute.resourcePolicies.delete sulla policy risorse
    • compute.disks.removeResourcePolicies sul disco

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

Visualizzare le pianificazioni degli snapshot

Per ottenere un elenco di pianificazioni degli snapshot, utilizza la console, il comando gcloud o il metodo dell'API Compute Engine. Questa richiesta mostra il nome, la descrizione e la regione di tutte le pianificazioni snapshot all'interno di un progetto.

Console

  1. Nella console Google Cloud vai alla pagina Snapshot.

    Vai alla pagina Snapshot

  2. Seleziona la scheda Pianificazioni snapshot.
  3. Utilizza il campo Filtra per restringere l'elenco delle pianificazioni snapshot.
  4. Fai clic sul nome di una pianificazione degli snapshot per visualizzarne i dettagli.

gcloud

Per visualizzare un elenco delle pianificazioni di snapshot, utilizza il comando resource-policies list.

 gcloud compute resource-policies list

Per visualizzare la descrizione di una pianificazione di snapshot specifica, utilizza il comando resource-policies describe.

gcloud compute resource-policies describe SCHEDULE_NAME

Sostituisci SCHEDULE_NAME con il nome della pianificazione di snapshot.

Vai

Elenco delle pianificazioni degli snapshot

import (
	"context"
	"fmt"
	"io"

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

// listSnapshotSchedule retrieves a list of snapshot schedules.
func listSnapshotSchedule(w io.Writer, projectID, region, filter string) error {
	// projectID := "your_project_id"
	// snapshotName := "your_snapshot_name"
	// region := "eupore-central2"

	// Formatting for filters:
	// https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.ListResourcePoliciesRequest

	ctx := context.Background()

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

	req := &computepb.ListResourcePoliciesRequest{
		Project: projectID,
		Region:  region,
		Filter:  proto.String(filter),
	}
	it := snapshotsClient.List(ctx, req)

	for {
		policy, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s", policy.GetName())
	}
	return nil
}

Descrivi una pianificazione snapshot

import (
	"context"
	"fmt"
	"io"

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

// getSnapshotSchedule gets a snapshot schedule.
func getSnapshotSchedule(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.GetResourcePolicyRequest{
		Project:        projectID,
		Region:         region,
		ResourcePolicy: scheduleName,
	}
	schedule, err := snapshotsClient.Get(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get snapshot schedule: %w", err)
	}

	fmt.Fprintf(w, "Found snapshot schedule: %s\n", schedule.GetName())

	return nil
}

Java

Elenco delle pianificazioni degli snapshot

import com.google.cloud.compute.v1.ListResourcePoliciesRequest;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import com.google.cloud.compute.v1.ResourcePoliciesClient.ListPagedResponse;
import com.google.cloud.compute.v1.ResourcePolicy;
import java.io.IOException;

public class ListSnapshotSchedules {

  public static void main(String[] args) throws IOException {
    // 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 you want to list snapshot schedules from.
    String region = "us-central1";
    // Name of the snapshot schedule you want to list.
    String snapshotScheduleName = "YOUR_SCHEDULE_NAME";

    listSnapshotSchedules(projectId, region, snapshotScheduleName);
  }

  // Lists snapshot schedules in a specified region, optionally filtered.
  public static ListPagedResponse listSnapshotSchedules(
          String projectId, String region, String snapshotScheduleName) throws IOException {
    String filter = String.format("name = %s", 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 (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {

      ListResourcePoliciesRequest request = ListResourcePoliciesRequest.newBuilder()
              .setProject(projectId)
              .setRegion(region)
              .setFilter(filter)
              .build();
      ListPagedResponse response = resourcePoliciesClient.list(request);
      for (ResourcePolicy resourcePolicy : response.iterateAll()) {
        System.out.println(resourcePolicy);
      }
      return response;
    }
  }
}

Descrivere una pianificazione snapshot

import com.google.cloud.compute.v1.GetResourcePolicyRequest;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import com.google.cloud.compute.v1.ResourcePolicy;
import java.io.IOException;

public class GetSnapshotSchedule {

  public static void main(String[] args) throws IOException {
    // 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 your snapshot schedule is located.
    String region = "us-central1";
    // Name of your snapshot schedule.
    String snapshotScheduleName = "YOUR_SCHEDULE_NAME";

    getSnapshotSchedule(projectId, region, snapshotScheduleName);
  }

  // Retrieves the details of a snapshot schedule.
  public static ResourcePolicy getSnapshotSchedule(
        String projectId, String region, String snapshotScheduleName) throws IOException {
    // 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()) {
      GetResourcePolicyRequest request = GetResourcePolicyRequest.newBuilder()
              .setProject(projectId)
              .setRegion(region)
              .setResourcePolicy(snapshotScheduleName)
              .build();
      ResourcePolicy resourcePolicy = resourcePoliciesClient.get(request);
      System.out.println(resourcePolicy);

      return resourcePolicy;
    }
  }
}

Node.js

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

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

/**
 * 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';

async function callGetSnapshotSchedule() {
  const [response] = await resourcePoliciesClient.get({
    project: projectId,
    region,
    resourcePolicy: snapshotScheduleName,
  });

  console.log(JSON.stringify(response));
}

await callGetSnapshotSchedule();

Python

Elenco delle pianificazioni degli snapshot

from google.cloud import compute_v1
from google.cloud.compute_v1.services.resource_policies import pagers


def snapshot_schedule_list(project_id: str, region: str) -> pagers.ListPager:
    """
    Lists snapshot schedules for a specified project and region.
    Args:
        project_id (str): The ID of the Google Cloud project.
        region (str): The region where the snapshot schedules are located.
    Returns:
        ListPager: A pager for iterating through the list of snapshot schedules.
    """
    client = compute_v1.ResourcePoliciesClient()

    request = compute_v1.ListResourcePoliciesRequest(
        project=project_id,
        region=region,
        filter='status = "READY"',  # Optional filter
    )

    schedules = client.list(request=request)
    return schedules

Descrivi una pianificazione snapshot

from google.cloud import compute_v1


def snapshot_schedule_get(
    project_id: str, region: str, snapshot_schedule_name: str
) -> compute_v1.ResourcePolicy:
    """
    Retrieves a snapshot schedule 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 is located.
        snapshot_schedule_name (str): The name of the snapshot schedule.
    Returns:
        compute_v1.ResourcePolicy: The retrieved snapshot schedule.
    """
    client = compute_v1.ResourcePoliciesClient()
    schedule = client.get(
        project=project_id, region=region, resource_policy=snapshot_schedule_name
    )
    return schedule

REST

Crea una richiesta GET a resourcePolicies.aggregatedList per restituire un elenco delle pianificazioni di snapshot per un progetto.

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/aggregated/resourcePolicies

Sostituisci PROJECT_ID con il nome del progetto.

Visualizzare le pianificazioni degli snapshot per regione

Per visualizzare le pianificazioni di snapshot per un progetto all'interno di una determinata regione, utilizza la consoleGoogle Cloud , gcloud CLI o REST.

Console

  1. Nella console Google Cloud vai alla pagina Snapshot.

    Vai alla pagina Snapshot

  2. Seleziona la scheda Pianificazioni snapshot.
  3. Utilizza il campo Filtra per elencare le pianificazioni degli snapshot per una regione specifica.

gcloud

Per visualizzare le pianificazioni di snapshot per un progetto all'interno di una regione specifica, usa il comando resource-policies list.

gcloud compute resource-policies list PROJECT_ID --filter REGION

Sostituisci quanto segue:

  • PROJECT_ID: il nome del progetto.
  • REGION: la regione, ad esempio us-west1

REST

Invia una richiesta GET al metodo resourcePolicies.list per recuperare le pianificazioni di snapshot create in una regione.

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

Sostituisci quanto segue:

  • PROJECT_ID: il nome del progetto.
  • REGION: la regione, ad esempio us-west1

Modificare una pianificazione snapshot

Dopo aver creato una pianificazione degli snapshot, puoi modificare dinamicamente i seguenti campi utilizzando la procedura Aggiorna una pianificazione degli snapshot:

  • Descrizione
  • Pianificazione snapshot
  • Etichette applicate agli snapshot generati
  • Criterio di eliminazione del disco di origine per la gestione degli snapshot generati automaticamente se il disco di origine viene eliminato
  • Policy di conservazione per definire per quanto tempo conservare gli snapshot generati dalla pianificazione degli snapshot

Per aggiornare altri valori per una pianificazione snapshot, devi eliminare la pianificazione snapshot e crearne una nuova, come descritto in Sostituire una pianificazione snapshot.

Gli aggiornamenti della pianificazione degli snapshot diventano effettivi nel primo snapshot dopo gli aggiornamenti. Se uno snapshot è in esecuzione durante l'aggiornamento della pianificazione degli snapshot, le modifiche diventano effettive nello snapshot successivo.

Aggiorna una pianificazione snapshot

Puoi utilizzare Google Cloud CLI o l'API Compute Engine per modificare alcune proprietà della pianificazione degli snapshot, come descritto in Modificare una pianificazione degli snapshot.

Per modificare altre proprietà della pianificazione snapshot, utilizza il metodo descritto in Sostituire una pianificazione snapshot.

Console

  1. Nella console Google Cloud vai alla pagina Snapshot.

    Vai alla pagina Snapshot

  2. Seleziona Pianificazioni di snapshot per visualizzare un elenco delle tue pianificazioni.
  3. Fai clic sul nome della pianificazione degli snapshot da modificare.
  4. Nella pagina dei dettagli della pianificazione degli snapshot, fai clic sul pulsante Modifica pianificazione.

gcloud

Utilizza il comando compute resource-policies update per aggiornare la descrizione, la pianificazione, la policy di conservazione o le etichette di una pianificazione snapshot.

gcloud compute resource-policies update snapshot-schedule SCHEDULE_NAME \
   --region=REGION \
   --description="DESCRIPTION" \
   --snapshot-labels="KEY=VALUE" \
   --max-retention-days=DAYS \
   --on-source-disk-delete=DELETE_OPTION \
   --start-time=START_TIME \
   SCHEDULE_FLAG

Sostituisci quanto segue:

  • SCHEDULE_NAME: il nome della pianificazione di snapshot.
  • REGION: la regione in cui si trova la pianificazione di snapshot.
  • DESCRIPTION: una descrizione della pianificazione di snapshot. Racchiudi la descrizione tra virgolette.
  • KEY e VALUE: una coppia chiave-valore che può essere utilizzata per raggruppare risorse correlate o associate.
  • DAYS: Numero massimo di giorni in cui lo snapshot viene conservato prima di essere eliminato.
  • DELETE_OPTION: comportamento di conservazione degli snapshot automatici dopo l'eliminazione del disco originale. Il valore deve essere uno dei seguenti:
    • apply-retention-policy: quando il disco di origine viene eliminato, continua ad applicare il periodo di conservazione a tutti gli snapshot creati dalla pianificazione di snapshot.
    • keep-auto-snapshots: (impostazione predefinita) se il disco di origine viene eliminato, conserva gli snapshot creati dalla pianificazione snapshot, indipendentemente dalla finestra di conservazione.
  • START_TIME: l'ora di inizio in formato UTC. L'ora deve essere un'ora piena. Ad esempio:
    • Le 14:00 PST sono le 22:00.
    • Se imposti un'ora di inizio pari a 22:13, riceverai un errore.
  • SCHEDULE_FLAG: uno dei seguenti flag:

    • --hourly-schedule=HOURLY_INTERVAL: il numero di ore tra ogni snapshot. HOURLY_INTERVAL deve essere un numero intero compreso tra 1 e 23. Ad esempio, se imposti --hourly-schedule su 12, lo snapshot viene generato ogni 12 ore.
    • --daily-schedule: esegue uno snapshot giornaliero alle START_TIME
    • --weekly-schedule=WEEKLY_INTERVAL: definisce il giorno in cui vuoi che venga eseguito lo snapshot. Devi scrivere per esteso il giorno della settimana; i valori non sono sensibili alle maiuscole.

    • --weekly-schedule-from-file=FILE_NAME: specifica un file che contiene la pianificazione di snapshot settimanale. Puoi specificare pianificazioni settimanali in giorni diversi della settimana e in orari diversi utilizzando un file. Ad esempio, il file potrebbe specificare una pianificazione degli snapshot il lunedì e il mercoledì: none [{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}] Se includi un'ora di inizio nel file, non devi impostare il flag --start-time. La pianificazione utilizza il fuso orario UTC. L'ora di inizio deve essere un'ora piena. Ad esempio:

      • Le 14:00 PST sono le 22:00.
      • Se imposti un'ora di inizio pari a 22:13, riceverai un errore.

    I flag di frequenza degli snapshot hourly-schedule, daily-schedule, weekly-schedule e weekly-schedule-from-file si escludono a vicenda. Puoi utilizzarne solo uno per la pianificazione di snapshot.

Esempi:

Per modificare una pianificazione snapshot in una pianificazione giornaliera:

gcloud compute resource-policies update snapshot-schedule SCHEDULE_NAME \
    --region=REGION --daily-schedule --start-time=START_TIME

Per modificare uno snapshot in una pianificazione oraria e aggiornare anche la descrizione e l'etichetta dello snapshot:

gcloud compute resource-policies update snapshot-schedule SCHEDULE_NAME \
    --region=REGION --description="DESCRIPTION" \
    --hourly-schedule=HOURLY_INTERVAL --start-time=START_TIME \
    --snapshot-labels="KEY=VALUE"

Per modificare le norme di conservazione degli snapshot e di eliminazione del disco di origine per una pianificazione degli snapshot:

gcloud compute resource-policies update snapshot-schedule SCHEDULE_NAME \
    --region=REGION --max-retention-days=DAYS \
    --on-source-disk-delete=DELETE_OPTION

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"
)

// editSnapshotSchedule edits a snapshot schedule.
func editSnapshotSchedule(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.PatchResourcePolicyRequest{
		Project:        projectID,
		Region:         region,
		ResourcePolicy: scheduleName,
		ResourcePolicyResource: &computepb.ResourcePolicy{
			Name:        proto.String(scheduleName),
			Description: proto.String("MY HOURLY SNAPSHOT SCHEDULE"),
			SnapshotSchedulePolicy: &computepb.ResourcePolicySnapshotSchedulePolicy{
				Schedule: &computepb.ResourcePolicySnapshotSchedulePolicySchedule{
					HourlySchedule: &computepb.ResourcePolicyHourlyCycle{
						HoursInCycle: proto.Int32(12),
						StartTime:    proto.String("22:00"),
					},
				},
			},
		},
	}
	op, err := snapshotsClient.Patch(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 changed\n")

	return nil
}

Java

import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.PatchResourcePolicyRequest;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import com.google.cloud.compute.v1.ResourcePolicy;
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 com.google.cloud.compute.v1.ResourcePolicyWeeklyCycle;
import com.google.cloud.compute.v1.ResourcePolicyWeeklyCycleDayOfWeek;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class EditSnapshotSchedule {

  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 region where your snapshot schedule is located.
    String region = "us-central1";
    // Name of the snapshot schedule you want to update.
    String snapshotScheduleName = "YOUR_SCHEDULE_NAME";

    editSnapshotSchedule(projectId, region, snapshotScheduleName);
  }

  // Edits a snapshot schedule.
  public static Status editSnapshotSchedule(
          String projectId, String region, String snapshotScheduleName)
          throws IOException, InterruptedException, ExecutionException, 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()) {
      Map<String, String> snapshotLabels = new HashMap<>();
      snapshotLabels.put("key", "value");

      ResourcePolicySnapshotSchedulePolicySnapshotProperties.Builder snapshotProperties =
              ResourcePolicySnapshotSchedulePolicySnapshotProperties.newBuilder();
      snapshotProperties.putAllLabels(snapshotLabels);

      ResourcePolicyWeeklyCycleDayOfWeek dayOfWeek = ResourcePolicyWeeklyCycleDayOfWeek.newBuilder()
              .setDay("Tuesday")
              .setStartTime("09:00")
              .build();
      ResourcePolicyWeeklyCycle weeklySchedule = ResourcePolicyWeeklyCycle.newBuilder()
              .addDayOfWeeks(dayOfWeek)
              .build();

      int maxRetentionDays = 3;

      ResourcePolicySnapshotSchedulePolicyRetentionPolicy.Builder retentionPolicy =
              ResourcePolicySnapshotSchedulePolicyRetentionPolicy.newBuilder();
      retentionPolicy.setOnSourceDiskDelete(OnSourceDiskDelete.APPLY_RETENTION_POLICY.toString());
      retentionPolicy.setMaxRetentionDays(maxRetentionDays);

      String description = "Updated description";

      ResourcePolicy updatedSchedule = ResourcePolicy.newBuilder()
              .setName(snapshotScheduleName)
              .setDescription(description)
              .setSnapshotSchedulePolicy(
                      ResourcePolicySnapshotSchedulePolicy.newBuilder()
                              .setSchedule(ResourcePolicySnapshotSchedulePolicySchedule.newBuilder()
                                      .setWeeklySchedule(weeklySchedule))
                              .setSnapshotProperties(snapshotProperties)
                              .setRetentionPolicy(retentionPolicy.build())
                              .build())
              .build();

      PatchResourcePolicyRequest request = PatchResourcePolicyRequest.newBuilder()
              .setProject(projectId)
              .setRegion(region)
              .setResourcePolicy(snapshotScheduleName)
              .setResourcePolicyResource(updatedSchedule)
              .build();

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

      if (response.hasError()) {
        throw new Error("Failed to update snapshot schedule! " + 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';

async function callEditSnapshotSchedule() {
  const [response] = await resourcePoliciesClient.patch({
    project: projectId,
    region,
    resourcePolicy: snapshotScheduleName,
    resourcePolicyResource: compute.ResourcePolicy({
      snapshotSchedulePolicy:
        compute.ResourcePolicyInstanceSchedulePolicySchedule({
          schedule: compute.ResourcePolicySnapshotSchedulePolicySchedule({
            weeklySchedule: compute.ResourcePolicyWeeklyCycle({
              dayOfWeeks: [
                compute.ResourcePolicyWeeklyCycleDayOfWeek({
                  day: 'Tuesday',
                  startTime: '9:00',
                }),
              ],
            }),
          }),
        }),
    }),
  });

  let operation = response.latestResponse;

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

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

await callEditSnapshotSchedule();

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_update(
    project_id: str,
    region: str,
    schedule_name: str,
    schedule_description: str,
    labels: dict,
) -> compute_v1.ResourcePolicy:
    """
    Updates a snapshot schedule 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 is located.
        schedule_name (str): The name of the snapshot schedule to update.
        schedule_description (str): The new description for the snapshot schedule.
        labels (dict): A dictionary of new labels to apply to the snapshot schedule.
    Returns:
        compute_v1.ResourcePolicy: The updated snapshot schedule.
    """

    # 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])

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

    # Autodelete snapshots after 10 days
    retention_policy = compute_v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy(
        max_retention_days=10
    )
    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.patch(
        project=project_id,
        region=region,
        resource_policy=schedule_name,
        resource_policy_resource=resource_policy_resource,
    )
    wait_for_extended_operation(operation, "Resource Policy updating")

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

REST

Crea una richiesta PATCH al metodo resourcePolicies per aggiornare la descrizione, la pianificazione, la policy di conservazione, la policy di eliminazione del disco di origine o le etichette di una pianificazione di snapshot. Nel corpo della richiesta, devi specificare solo name e i campi che vuoi aggiornare.

  • Modifica la descrizione e l'etichetta:

    PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME
    {
        "name": "SCHEDULE_NAME",
        "description": "DESCRIPTION",
        "snapshotProperties": {
            "labels": {"KEY": "VALUE"}
        }
    }
    
  • Modifica la pianificazione degli snapshot in modo che vengano creati ogni ora:

    PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME
    {
        "name": "SCHEDULE_NAME",
        "snapshotSchedulePolicy": {
            "schedule": {
              "hourlySchedule": {
                  "hoursInCycle": HOURLY_INTERVAL,
                  "startTime": START_TIME
               }
            }
        }
    }
    
  • Modifica la pianificazione degli snapshot in giornaliera:

    PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME
    {
        "name": "SCHEDULE_NAME",
        "snapshotSchedulePolicy": {
            "schedule": {
              "dailySchedule": {
                  "daysInCycle": DAILY_INTERVAL,
                  "startTime": START_TIME
               }
            }
        }
    }
    
  • Modifica la pianificazione degli snapshot in settimanale:

    PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME
    {
        "name": "SCHEDULE_NAME",
        "snapshotSchedulePolicy": {
            "schedule": {
               "weeklySchedule": {
                  "dayOfWeeks": [
                     {
                        "day": WEEKLY_INTERVAL,
                        "startTime": START_TIME
                     }
                  ]
               }
            }
        }
    }
    
  • Modifica il criterio di conservazione degli snapshot:

    PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME
    {
        "name": "SCHEDULE_NAME",
        "snapshotSchedulePolicy": {
            "retentionPolicy": {
                "maxRetentionDays": DAYS,
                "onSourceDiskDelete":"DELETE_OPTION"
            }
       }
    }
    

Sostituisci quanto segue:

  • PROJECT_ID: il nome del progetto.
  • REGION: la regione in cui si trova la pianificazione di snapshot.
  • SCHEDULE_NAME: il nome della pianificazione di snapshot.
  • DESCRIPTION: una descrizione della pianificazione di snapshot. Racchiudi la descrizione tra virgolette.
  • KEY e VALUE: una coppia chiave-valore che può essere utilizzata per raggruppare risorse correlate o associate.
  • HOURLY_INTERVAL: definisce l'intervallo in cui vuoi che venga eseguito lo snapshot. Imposta la pianificazione oraria utilizzando un numero intero compreso tra 1 e 23. Per creare gli snapshot alla stessa ora ogni giorno, scegli un numero che sia divisibile per 24 (1, 2, 3, 4, 6, 8 o 12). Ad esempio, se imposti --hourly-schedule su 12, lo snapshot viene generato ogni 12 ore.
  • DAILY_INTERVAL: definisce il numero di giorni tra uno snapshot e l'altro. Per creare uno snapshot ogni giorno, utilizza il valore 1.
  • WEEKLY_INTERVAL: definisce una pianificazione che viene eseguita in giorni specifici della settimana. Specifica uno o più giorni. Sono disponibili le seguenti opzioni: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY e SUNDAY. Devi scrivere per esteso i giorni della settimana; non sono sensibili alle maiuscole. Puoi definire fino a 7 intervalli per dayOfWeeks, uno per ogni giorno della settimana.
  • START_TIME: l'ora di inizio in formato UTC. L'ora di inizio deve essere un'ora piena. Ad esempio:
    • Le 14:00 PST corrispondono alle 22:00 UTC.
    • Se imposti un'ora di inizio pari a 22:13, riceverai un errore.
  • DAYS: Numero massimo di giorni in cui lo snapshot viene conservato prima di essere eliminato.
  • DELETE_OPTION: comportamento di conservazione degli snapshot automatici dopo l'eliminazione del disco originale. Il valore deve essere uno dei seguenti:
    • APPLY_RETENTION_POLICY: quando il disco di origine viene eliminato, continua ad applicare il periodo di conservazione a tutti gli snapshot creati dalla pianificazione di snapshot.
    • KEEP_AUTO_SNAPSHOTS: (impostazione predefinita) se il disco di origine viene eliminato, conserva gli snapshot creati dalla pianificazione snapshot, indipendentemente dalla finestra di conservazione.

Sostituisci una pianificazione snapshot

Per eliminare la pianificazione degli snapshot e crearne una nuova: Utilizza questo metodo per modificare le proprietà della pianificazione snapshot che non possono essere modificate utilizzando la procedura Aggiorna una pianificazione snapshot.

Se stai sostituendo una pianificazione di snapshot già collegata a un disco, devi prima scollegarla dal disco ed eliminarla. Quindi puoi creare una nuova pianificazione e collegarla al disco.

Gli snapshot generati dalla pianificazione di snapshot scollegata non verranno gestiti dal nuovo criterio. Questi snapshot verranno conservati per un periodo di tempo indefinito fino a quando non li eliminerai.

Utilizza la console Google Cloud , gcloud CLI o REST per rimuovere e sostituire la pianificazione di snapshot.

Console

  1. Nella console Google Cloud vai alla pagina Dischi.

    Vai alla pagina Dischi

  2. Seleziona il disco con la pianificazione che vuoi scollegare.
  3. Nella pagina Gestisci disco, fai clic su Modifica. Potresti prima dover fare clic sul menu Altre azioni.
  4. Apri il menu a discesa Pianificazione snapshot.
  5. Fai clic su Nessuna pianificazione per scollegare la pianificazione dal disco.
  6. Puoi creare una nuova pianificazione o scambiarla mentre modifichi le opzioni del disco.
  7. Fai clic su Salva per completare l'attività.

gcloud

  1. Utilizza il comando gcloud disks remove-resource-policies per scollegare la pianificazione di snapshot dal disco con la pianificazione che vuoi modificare.

    gcloud compute disks remove-resource-policies DISK_NAME \
        --resource-policies SCHEDULE_NAME \
        --region REGION \
        --zone ZONE
    

    Sostituisci quanto segue:

    • DISK_NAME: il nome del disco a cui è collegata la pianificazione di snapshot
    • SCHEDULE_NAME: il nome della pianificazione di snapshot che vuoi scollegare da questo disco
    • REGION: la regione in cui si trova la pianificazione di snapshot
    • ZONE: la zona in cui si trova il disco zonale
  2. Utilizza il comando gcloud disks add-resource-policies per aggiungere la nuova pianificazione snapshot al disco.

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

    Sostituisci quanto segue:

    • DISK_NAME: il nome del disco con la policy risorse della pianificazione di snapshot
    • SCHEDULE_NAME: il nome della pianificazione di snapshot che vuoi aggiungere a questo disco
    • ZONE: la zona in cui si trova il disco

REST

  1. Scollega la pianificazione di snapshot corrente da un disco creando una richiesta POST a disks.removeResourcePolicies.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks/DISK_NAME/removeResourcePolicies
    
    {
      "resourcePolicies": [
         "regions/REGION/resourcePolicies/SCHEDULE_NAME"
      ]
    }
    

    Sostituisci quanto segue:

    • PROJECT_ID: il nome del progetto.
    • ZONE: la zona in cui si trova il disco
    • DISK_NAME: il nome del disco con la pianificazione di snapshot associata.
    • REGION: la posizione della pianificazione di snapshot
    • SCHEDULE_NAME: il nome della pianificazione di snapshot che stai rimuovendo da questo disco
  2. Collega la nuova pianificazione di snapshot al disco creando una richiesta POST al metodo disks.addResourcePolicies.

    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 posizione del disco
    • DISK_NAME: il nome del disco
    • REGION: la posizione della pianificazione di snapshot
    • SCHEDULE_NAME: il nome della pianificazione di snapshot che stai applicando a questo disco

Elimina una pianificazione snapshot

Se elimini una pianificazione snapshot, tutti gli snapshot generati automaticamente associati alla pianificazione snapshot vengono conservati in modo permanente. Tuttavia, dopo l'eliminazione della pianificazione, non può più generare snapshot.

La policy di conservazione fa parte della pianificazione degli snapshot. Una volta eliminata la pianificazione, la tua norma di conservazione non viene più applicata. Gli snapshot già generati vengono conservati in modo permanente finché non li elimini manualmente.

Per eliminare una pianificazione di snapshot esistente, utilizza la consoleGoogle Cloud , Google Cloud CLI o il metodo dell'API Compute Engine. Se la pianificazione è già collegata a un disco, scollega la pianificazione dal disco, quindi elimina la pianificazione. Non puoi eliminare una pianificazione degli snapshot collegata a un disco.

Console

  1. Nella console Google Cloud vai alla pagina Snapshot.

    Vai alla pagina Snapshot

  2. Seleziona Pianificazioni di snapshot per visualizzare un elenco delle tue pianificazioni.
  3. Seleziona una pianificazione non associata a un disco.
  4. Fai clic su Elimina.

gcloud

Per eliminare una pianificazione di snapshot, utilizza il comando resource-policies delete.

gcloud compute resource-policies delete SCHEDULE_NAME \
    --region REGION

Sostituisci quanto segue:

  • SCHEDULE_NAME: il nome della pianificazione di snapshot
  • REGION: la posizione della pianificazione di snapshot

Vai

import (
	"context"
	"fmt"
	"io"

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

// deleteSnapshotSchedule deletes a snapshot schedule.
func deleteSnapshotSchedule(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.DeleteResourcePolicyRequest{
		Project:        projectID,
		Region:         region,
		ResourcePolicy: scheduleName,
	}
	op, err := snapshotsClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete 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 deleted\n")

	return nil
}

Java

import com.google.cloud.compute.v1.DeleteResourcePolicyRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.ResourcePoliciesClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteSnapshotSchedule {
  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 where your snapshot schedule is located.
    String region = "us-central1";
    // Name of the snapshot schedule you want to delete.
    String snapshotScheduleName = "YOUR_SCHEDULE_NAME";

    deleteSnapshotSchedule(projectId, region, snapshotScheduleName);
  }

  // Deletes a snapshot schedule policy.
  public static Status deleteSnapshotSchedule(
          String projectId, String region, 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 (ResourcePoliciesClient resourcePoliciesClient = ResourcePoliciesClient.create()) {
      DeleteResourcePolicyRequest request = DeleteResourcePolicyRequest.newBuilder()
              .setProject(projectId)
              .setRegion(region)
              .setResourcePolicy(snapshotScheduleName)
              .build();
      Operation response = resourcePoliciesClient.deleteAsync(request).get(3, TimeUnit.MINUTES);

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

Node.js

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

// 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'

async function callDeleteSnapshotSchedule() {
  // If the snapshot schedule is already attached to a disk, you will receive an error.
  const [response] = await resourcePoliciesClient.delete({
    project: projectId,
    region,
    resourcePolicy: snapshotScheduleName,
  });

  let operation = response.latestResponse;

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

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

await callDeleteSnapshotSchedule();

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_delete(
    project_id: str, region: str, snapshot_schedule_name: str
) -> None:
    """
    Deletes a snapshot schedule 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 is located.
        snapshot_schedule_name (str): The name of the snapshot schedule to delete.
    Returns:
        None
    """
    client = compute_v1.ResourcePoliciesClient()
    operation = client.delete(
        project=project_id, region=region, resource_policy=snapshot_schedule_name
    )
    wait_for_extended_operation(operation, "Resource Policy deletion")

REST

Per eliminare una pianificazione snapshot, invia una richiesta DELETE al metodo resourcePolicies.delete. Se la pianificazione di snapshot è già collegata a un disco, riceverai un errore.

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

Sostituisci quanto segue:

  • PROJECT_ID: il nome del progetto.
  • REGION: la posizione della pianificazione di snapshot
  • SCHEDULE_NAME: il nome della pianificazione di snapshot

Logging e monitoraggio

Ogni snapshot pianificato associato a un disco crea continuamente un evento di sistema, che viene monitorato e registrato in ogni momento. Gli audit log degli eventi di sistema sono sempre attivi.

Questi log forniscono informazioni sul comportamento degli snapshot pianificati per ogni disco associato. Puoi visualizzare i log dal menu Logging nella console Google Cloud .

Per saperne di più sull'utilizzo di Esplora log, consulta Visualizzare i log utilizzando Esplora log.

Console

  1. Nella console Google Cloud , vai alla pagina Esplora log.

    Vai alla pagina Esplora log

  2. Nell'elenco a discesa Tutte le risorse, seleziona Disco e poi Tutti gli ID disco.

  3. Nell'elenco a discesa Tutti i log, seleziona cloudaudit.googleapis.com/system_event e fai clic su Ok.

  4. Nell'elenco a discesa Qualsiasi livello di log, seleziona il tipo di log.

Passaggi successivi