Gestire le pianificazioni degli snapshot per i dischi


Questo documento descrive come gestire le pianificazioni degli snapshot per i dischi permanenti a livello di zona e di regione e per Hyperdisk di Google Cloud.

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 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 visualizzare le pianificazioni degli snapshot: compute.resourcePolicies.list nel progetto o nell'organizzazione
  • Per aggiornare una pianificazione di snapshot:
    • compute.resourcePolicies.update nel criterio delle risorse
    • compute.resourcePolicies.get nel criterio delle risorse
  • Per sostituire una pianificazione degli snapshot:
    • compute.resourcePolicies.use nel criterio delle risorse
    • compute.disks.addResourcePolicies sul disco
    • compute.disks.removeResourcePolicies sul disco
  • Per eliminare una pianificazione snapshot:
    • compute.resourcePolicies.delete nel criterio delle 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 delle 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 degli 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 degli snapshot.
  3. Utilizza il campo Filtra per restringere l'elenco delle pianificazioni degli snapshot.
  4. Fai clic sul nome di una pianificazione degli istantanei per visualizzarne i dettagli.

gcloud

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

 gcloud compute resource-policies list

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

gcloud compute resource-policies describe SCHEDULE_NAME

Sostituisci SCHEDULE_NAME con il nome della pianificazione degli snapshot.

Vai

Elenco delle pianificazioni di 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 di 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 di 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

Invia una richiesta GET a resourcePolicies.aggregatedList per restituire un elenco delle pianificazioni degli 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 degli snapshot per un progetto all'interno di una determinata regione, utilizza la console Google Cloud, gcloud CLI o REST.

Console

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

    Vai alla pagina Snapshot

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

gcloud

Per visualizzare le pianificazioni degli snapshot per un progetto all'interno di una regione specifica, utilizza 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 degli snapshot

Dopo aver creato una pianificazione degli snapshot, puoi modificare i seguenti campi dinamicamente utilizzando la procedura Aggiornare 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
  • Criterio di conservazione per definire per quanto tempo conservare gli snapshot generati dalla pianificazione degli snapshot

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

Gli aggiornamenti della pianificazione degli snapshot vengono applicati nel primo snapshot dopo gli aggiornamenti. Se è in corso uno snapshot mentre aggiorni la relativa pianificazione, le modifiche verranno applicate nell'istantanea successiva.

Aggiorna una pianificazione snapshot

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

Per modificare altre proprietà della pianificazione degli snapshot, utilizza il metodo descritto in Sostituisci una pianificazione degli 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 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, il criterio di conservazione o le etichette di una pianificazione degli 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 degli snapshot.
  • REGION: la regione in cui risiede la programmazione degli snapshot.
  • DESCRIPTION: una descrizione della pianificazione degli snapshot. Racchiudi la descrizione tra virgolette.
  • KEY e VALUE: una coppia chiave-valore che può essere utilizzata per raggruppare le risorse correlate o associate.
  • DAYS: numero massimo di giorni prima che lo snapshot venga 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 la finestra di conservazione per tutti gli snapshot creati dalla pianificazione degli snapshot.
    • keep-auto-snapshots: (valore predefinito) se il disco di origine viene eliminato, mantieni gli snapshot creati dalla pianificazione degli snapshot, indipendentemente dalla finestra di conservazione.
  • START_TIME: l'ora di inizio UTC. L'ora deve iniziare sull'ora. Ad esempio:
    • Le 14:00 PST corrispondono a 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 istantanea. 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 ogni giorno alle ore 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 contenente la pianificazione degli snapshot settimanali. 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 istantanei di lunedì e mercoledì: none [{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}] Se nel file includi un'ora di inizio, non è necessario impostare il flag --start-time. La pianificazione utilizza il fuso orario UTC. L'ora deve iniziare a ora in punto. Ad esempio:

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

    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.

Esempi:

Per modificare la pianificazione degli 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 ogni ora 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 i criteri di conservazione degli snapshot e di eliminazione dei dischi di origine per una programmazione 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, il criterio di conservazione, il criterio di eliminazione del disco di origine o le etichette di una pianificazione di snapshot. Nel corpo della richiesta, devi solo specificare 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"}
        }
    }
    
  • Modificare la pianificazione degli snapshot su 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
               }
            }
        }
    }
    
  • Modificare la pianificazione degli snapshot su 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 degli snapshot.
  • SCHEDULE_NAME: il nome della pianificazione degli snapshot.
  • DESCRIPTION: una descrizione della pianificazione degli 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 deve avvenire lo snapshot. Imposta la pianificazione oraria utilizzando un numero intero tra 1 e 23. Per creare gli snapshot alla stessa ora ogni giorno, scegli un numero che si divida esattamente 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 ogni snapshot. Per creare uno snapshot ogni giorno, utilizza il valore 1.
  • WEEKLY_INTERVAL: consente di definire una pianificazione da eseguire 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 viene fatta distinzione tra maiuscole e minuscole. Puoi definire fino a 7 intervalli per dayOfWeeks, uno per ogni giorno della settimana.
  • START_TIME: l'ora di inizio UTC. L'ora deve essere obbligatoriamente un'ora piena. Ad esempio:
    • Le 14:00 PST corrispondono a 22:00 UTC.
    • Se imposti un'ora di inizio pari a 22:13, riceverai un errore.
  • DAYS: numero massimo di giorni prima che lo snapshot venga 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 la finestra di conservazione per tutti gli snapshot creati dalla pianificazione degli snapshot.
    • KEEP_AUTO_SNAPSHOTS: (valore predefinito) se il disco di origine viene eliminato, mantieni gli snapshot creati dalla pianificazione degli snapshot, indipendentemente dalla finestra di conservazione.

Sostituire 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 di aggiornamento di una pianificazione snapshot.

Se stai sostituendo una pianificazione di snapshot già collegata a un disco, devi prima scollegare la pianificazione dal disco ed eliminarla. Poi puoi creare un nuovo programma e collegarlo al disco.

Gli snapshot generati dalla pianificazione degli snapshot scollegata non verranno gestiti dal nuovo criterio. Questi snapshot verranno conservati a tempo indeterminato fino a quando non li elimini.

Utilizza la console Google Cloud, l'interfaccia a riga di comando gcloud o REST per rimuovere e sostituire la pianificazione degli snapshot.

Console

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

    Vai alla pagina Dischi

  2. Seleziona il disco contenente la pianificazione che vuoi scollegare.
  3. Nella pagina Gestisci disco, fai clic su Modifica. Potrebbe essere necessario fare prima clic sul menu Altre azioni.
  4. Apri il menu a discesa Pianificazione istantanee.
  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 degli 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 è associata la pianificazione degli snapshot
    • SCHEDULE_NAME: il nome della pianificazione di snapshot che vuoi scollegare da questo disco
    • REGION: la regione in cui risiede la pianificazione degli 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 degli 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 della risorsa di pianificazione degli snapshot
    • SCHEDULE_NAME: il nome della programmazione degli snapshot che vuoi aggiungere a questo disco
    • ZONE: la zona in cui si trova il disco

REST

  1. Scollega la pianificazione degli 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 degli snapshot associata
    • REGION: la posizione della pianificazione degli snapshot
    • SCHEDULE_NAME: il nome della pianificazione di snapshot che stai rimuovendo da questo disco
  2. Collega la nuova pianificazione degli 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 degli 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 vengono conservati definitivamente. Tuttavia, dopo l'eliminazione della pianificazione, non è più possibile generare istantanee.

Le norme di conservazione fanno parte della pianificazione degli snapshot. Una volta eliminata la pianificazione, il criterio di conservazione non viene più applicato. Gli istantanei già generati vengono conservati definitivamente finché non li elimini manualmente.

Per eliminare una pianificazione degli snapshot esistente, utilizza la console Google Cloud, Google Cloud CLI o il metodo dell'API Compute Engine. Se la pianificazione è già collegata a un disco, scollegala dal disco e poi eliminala. 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 pianificazioni.
  3. Seleziona una pianificazione non associata a un disco.
  4. Fai clic su Elimina.

gcloud

Per eliminare una pianificazione degli 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 degli snapshot
  • REGION: la posizione della pianificazione degli 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 degli snapshot, invia una richiesta DELETE al metodo resourcePolicies.delete. Se la pianificazione degli snapshot è già collegata a un disco, riceverai un messaggio di 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 degli snapshot
  • SCHEDULE_NAME: il nome della pianificazione degli 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 abilitati.

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

Per ulteriori informazioni sull'utilizzo di Esplora log, consulta Visualizza 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, posiziona il puntatore del mouse su Disco e seleziona Tutti i disk_id.

  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