Mengelola jadwal snapshot untuk disk


Dokumen ini menjelaskan cara mengelola jadwal snapshot untuk Persistent Disk zonal dan regional serta Hyperdisk Google Cloud.

Anda dapat mengelola jadwal snapshot sebagai berikut:

  • Melihat jadwal snapshot
  • Mengubah jadwal snapshot
  • Hapus beberapa jadwal snapshot

Anda juga dapat mengonfigurasi pemberitahuan untuk snapshot terjadwal.

Sebelum memulai

  • Jika Anda belum melakukannya, siapkan autentikasi. Autentikasi adalah proses yang digunakan untuk memverifikasi identitas Anda agar dapat mengakses Google Cloud layanan dan API. Untuk menjalankan kode atau contoh dari lingkungan pengembangan lokal, Anda dapat mengautentikasi ke Compute Engine dengan memilih salah satu opsi berikut:

    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. Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init
    2. Set a default region and zone.
    3. Go

      Untuk menggunakan contoh Go di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      Untuk informasi selengkapnya, lihat Set up authentication for a local development environment.

      Java

      Untuk menggunakan contoh Java di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      Untuk informasi selengkapnya, lihat Set up authentication for a local development environment.

      Node.js

      Untuk menggunakan contoh Node.js di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      Untuk informasi selengkapnya, lihat Set up authentication for a local development environment.

      Python

      Untuk menggunakan contoh Python di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. 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.

      Untuk informasi selengkapnya, lihat Set up authentication for a local development environment.

      REST

      Untuk menggunakan contoh REST API di halaman ini dalam lingkungan pengembangan lokal, gunakan kredensial yang Anda berikan ke gcloud CLI.

        Install the Google Cloud CLI, then initialize it by running the following command:

        gcloud init

      Untuk informasi selengkapnya, lihat Mengautentikasi untuk menggunakan REST dalam Google Cloud dokumentasi autentikasi.

Peran dan izin yang diperlukan

Untuk mendapatkan izin yang Anda perlukan untuk membuat jadwal snapshot, minta administrator untuk memberi Anda peran IAM berikut pada project:

Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Peran bawaan ini berisi izin yang diperlukan untuk membuat jadwal snapshot. Untuk melihat izin yang benar-benar diperlukan, luaskan bagian Izin yang diperlukan:

Izin yang diperlukan

Izin berikut diperlukan untuk membuat jadwal snapshot:

  • Untuk melihat jadwal snapshot: compute.resourcePolicies.list di project atau organisasi
  • Untuk memperbarui jadwal snapshot:
    • compute.resourcePolicies.update pada kebijakan resource
    • compute.resourcePolicies.get pada kebijakan resource
  • Untuk mengganti jadwal snapshot:
    • compute.resourcePolicies.use pada kebijakan resource
    • compute.disks.addResourcePolicies pada disk
    • compute.disks.removeResourcePolicies pada disk
  • Untuk menghapus jadwal snapshot:
    • compute.resourcePolicies.delete pada kebijakan resource
    • compute.disks.removeResourcePolicies pada disk

Anda mungkin juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaan lainnya.

Melihat jadwal snapshot

Untuk mendapatkan daftar jadwal snapshot, gunakan konsol, perintah gcloud, atau metode Compute Engine API. Permintaan ini menampilkan nama, deskripsi, dan region semua jadwal snapshot dalam sebuah project.

Konsol

  1. Di Konsol Google Cloud, buka halaman Snapshot.

    Buka halaman Snapshots

  2. Pilih tab Jadwal snapshot.
  3. Gunakan kolom Filter untuk mempersempit daftar jadwal snapshot.
  4. Klik nama jadwal snapshot untuk melihat detailnya.

gcloud

Untuk melihat daftar jadwal snapshot, gunakan perintah resource-policies list.

 gcloud compute resource-policies list

Untuk melihat deskripsi jadwal snapshot tertentu, gunakan perintah resource-policies describe.

gcloud compute resource-policies describe SCHEDULE_NAME

Ganti SCHEDULE_NAME dengan nama jadwal snapshot.

Go

Menampilkan daftar jadwal 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
}

Menjelaskan jadwal 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

Menampilkan daftar jadwal 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;
    }
  }
}

Mendeskripsikan jadwal 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

Menampilkan daftar jadwal 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

Menjelaskan jadwal 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

Buat permintaan GET ke resourcePolicies.aggregatedList untuk menampilkan daftar jadwal snapshot untuk sebuah project.

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

Ganti PROJECT_ID dengan nama project.

Melihat jadwal snapshot berdasarkan region

Untuk melihat jadwal snapshot untuk project dalam region tertentu, gunakan konsol Google Cloud, gcloud CLI, atau REST.

Konsol

  1. Di Konsol Google Cloud, buka halaman Snapshot.

    Buka halaman Snapshots

  2. Pilih tab Jadwal snapshot.
  3. Gunakan kolom Filter untuk mencantumkan jadwal snapshot untuk region tertentu.

gcloud

Untuk melihat jadwal snapshot project dalam region tertentu, gunakan perintah resource-policies list.

gcloud compute resource-policies list PROJECT_ID --filter REGION

Ganti kode berikut:

  • PROJECT_ID: nama project
  • REGION: region, misalnya us-west1

REST

Buat permintaan GET ke metode resourcePolicies.list untuk mengambil jadwal snapshot yang dibuat dalam suatu region.

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

Ganti kode berikut:

  • PROJECT_ID: nama project
  • REGION: region, misalnya us-west1

Mengubah jadwal snapshot

Setelah membuat jadwal snapshot, Anda dapat mengubah kolom berikut secara dinamis, menggunakan prosedur Mengupdate jadwal snapshot:

  • Deskripsi
  • Jadwal snapshot
  • Label diterapkan ke snapshot yang dibuat
  • Kebijakan penghapusan disk sumber untuk menangani snapshot yang dibuat secara otomatis jika disk sumber dihapus
  • Kebijakan retensi untuk menentukan durasi penyimpanan snapshot yang dihasilkan dari jadwal snapshot

Untuk memperbarui nilai lain untuk jadwal snapshot, Anda harus menghapus jadwal snapshot dan membuat yang baru, seperti yang dijelaskan dalam artikel Mengganti jadwal snapshot.

Pembaruan jadwal snapshot berlaku di snapshot pertama setelah update. Jika snapshot berjalan saat Anda memperbarui jadwal snapshot, perubahan akan diterapkan pada snapshot berikut.

Memperbarui jadwal snapshot

Anda dapat menggunakan Google Cloud CLI atau Compute Engine API untuk mengubah beberapa properti jadwal snapshot Anda, seperti yang dijelaskan dalam Mengubah jadwal snapshot.

Untuk mengubah properti lain dari jadwal snapshot Anda, gunakan metode yang dijelaskan dalam Mengganti jadwal snapshot.

Konsol

  1. Di Konsol Google Cloud, buka halaman Snapshot.

    Buka halaman Snapshot

  2. Pilih Jadwal snapshot untuk melihat daftar jadwal Anda.
  3. Klik nama jadwal snapshot yang ingin Anda ubah.
  4. Di halaman detail jadwal snapshot, klik tombol Edit jadwal.

gcloud

Gunakan perintah compute resource-policies update untuk memperbarui deskripsi, jadwal, kebijakan retensi, atau label jadwal 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

Ganti kode berikut:

  • SCHEDULE_NAME: nama jadwal snapshot.
  • REGION: region tempat jadwal snapshot Anda berada.
  • DESCRIPTION: deskripsi jadwal snapshot. Gunakan kutipan untuk deskripsi Anda.
  • KEY dan VALUE: pasangan nilai kunci yang dapat digunakan untuk mengelompokkan resource yang terhubung atau terkait.
  • DAYS: Jumlah maksimum hari snapshot disimpan sebelum dihapus.
  • DELETE_OPTION: Perilaku retensi snapshot otomatis setelah disk asli dihapus. Nilainya harus berupa salah satu dari:
    • apply-retention-policy: Saat disk sumber dihapus, terus terapkan periode retensi data untuk setiap snapshot yang dibuat berdasarkan jadwal snapshot.
    • keep-auto-snapshots: (Default) Jika disk sumber dihapus, simpan semua snapshot yang dibuat berdasarkan jadwal snapshot, terlepas dari periode retensi.
  • START_TIME: waktu mulai UTC. Waktu harus dimulai di awal jam. Misalnya:
    • 14.00 PST adalah 22:00.
    • Jika Anda menetapkan waktu mulai 22:13, Anda akan menerima error.
  • SCHEDULE_FLAG: salah satu flag berikut:

    • --hourly-schedule=HOURLY_INTERVAL: jumlah jam antara setiap snapshot. HOURLY_INTERVAL harus berupa bilangan bulat antara 1 dan 23. Misalnya, menetapkan --hourly-schedule ke 12, berarti snapshot dihasilkan setiap 12 jam.
    • --daily-schedule: menjalankan snapshot setiap hari, pada waktu START_TIME
    • --weekly-schedule=WEEKLY_INTERVAL: menentukan hari saat Anda ingin snapshot dilakukan. Anda harus menjelaskan hari kerja; nilai-nilainya tidak peka huruf besar/kecil.

    • --weekly-schedule-from-file=FILE_NAME: menentukan file yang berisi jadwal snapshot mingguan. Anda dapat menentukan jadwal mingguan pada hari yang berbeda dalam seminggu dan pada waktu yang berbeda menggunakan file. Misalnya, file Anda mungkin menentukan jadwal snapshot pada hari Senin dan Rabu: none [{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}] Jika Anda menyertakan waktu mulai dalam file, Anda tidak perlu menetapkan jadwal --start-time. Jadwal menggunakan zona waktu UTC. Waktu harus dimulai di awal jam. Contoh:

      • 14.00 PST adalah 22:00.
      • Jika Anda menetapkan waktu mulai 22:13, Anda akan menerima error.

    Flag frekuensi snapshot hourly-schedule, daily-schedule, weekly-schedule, dan weekly-schedule-from-file bersifat eksklusif satu sama lain. Anda hanya dapat menggunakan satu opsi untuk jadwal snapshot Anda.

Contoh:

Untuk mengubah jadwal snapshot ke jadwal harian:

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

Untuk mengubah snapshot menjadi jadwal per jam, dan juga memperbarui deskripsi dan label 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"

Untuk mengubah kebijakan retensi snapshot dan penghapusan disk sumber untuk jadwal snapshot:

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

Go

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

Buat permintaan PATCH ke metode resourcePolicies untuk memperbarui deskripsi, jadwal, kebijakan retensi, kebijakan penghapusan disk sumber, atau label jadwal snapshot. Dalam isi permintaan, Anda hanya perlu menentukan name dan kolom yang ingin diperbarui.

  • Mengubah deskripsi dan label:

    PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME
    {
        "name": "SCHEDULE_NAME",
        "description": "DESCRIPTION",
        "snapshotProperties": {
            "labels": {"KEY": "VALUE"}
        }
    }
    
  • Mengubah jadwal snapshot menjadi per jam:

    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
               }
            }
        }
    }
    
  • Mengubah jadwal snapshot menjadi harian:

    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
               }
            }
        }
    }
    
  • Mengubah jadwal snapshot menjadi mingguan:

    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
                     }
                  ]
               }
            }
        }
    }
    
  • Mengubah kebijakan retensi 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"
            }
       }
    }
    

Ganti kode berikut:

  • PROJECT_ID: nama project.
  • REGION: region tempat jadwal snapshot berada.
  • SCHEDULE_NAME: nama jadwal snapshot.
  • DESCRIPTION: deskripsi jadwal snapshot. Gunakan kutipan untuk deskripsi Anda.
  • KEY dan VALUE: pasangan nilai kunci yang dapat digunakan untuk mengelompokkan resource yang terhubung atau terkait.
  • HOURLY_INTERVAL: menentukan interval saat Anda ingin snapshot terjadi. Tetapkan jadwal per jam menggunakan bilangan bulat antara 1 dan 23. Agar snapshot dibuat pada waktu yang sama setiap hari, pilih angka yang dibagi secara merata menjadi 24 (1, 2, 3, 4, 6, 8, atau 12). Misalnya, menetapkan --hourly-schedule ke 12, berarti snapshot dihasilkan setiap 12 jam.
  • DAILY_INTERVAL: menentukan jumlah hari antara setiap snapshot. Untuk membuat snapshot setiap hari, gunakan nilai 1.
  • WEEKLY_INTERVAL: menentukan jadwal yang berjalan pada hari tertentu dalam seminggu. Tentukan satu atau beberapa hari. Opsi berikut tersedia: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, dan SUNDAY. Anda harus menguraikan hari kerja; mereka tidak peka huruf besar/kecil. Anda dapat menentukan hingga 7 interval untuk dayOfWeeks, satu interval untuk setiap hari dalam seminggu.
  • START_TIME: waktu mulai UTC. Waktu harus dimulai di awal jam. Misalnya:
    • 14.00 PST adalah 22:00 UTC.
    • Jika Anda menetapkan waktu mulai 22:13, Anda akan menerima error.
  • DAYS: Jumlah maksimum hari snapshot disimpan sebelum dihapus.
  • DELETE_OPTION: Perilaku retensi snapshot otomatis setelah disk asli dihapus. Nilainya harus berupa salah satu dari:
    • APPLY_RETENTION_POLICY: Saat disk sumber dihapus, terus terapkan periode retensi data untuk setiap snapshot yang dibuat berdasarkan jadwal snapshot.
    • KEEP_AUTO_SNAPSHOTS: (Default) Jika disk sumber dihapus, simpan semua snapshot yang dibuat berdasarkan jadwal snapshot, terlepas dari periode retensi.

Mengganti jadwal snapshot

Ikuti langkah-langkah berikut untuk menghapus jadwal snapshot dan membuat jadwal baru. Gunakan metode ini untuk mengubah properti jadwal snapshot yang tidak dapat diubah menggunakan prosedur memperbarui jadwal snapshot.

Jika Anda mengganti jadwal snapshot yang sudah terpasang ke disk, Anda harus terlebih dahulu melepaskan jadwal dari disk dan menghapusnya. Kemudian Anda dapat membuat jadwal baru, dan memasangnya ke disk.

Snapshot yang dihasilkan dari jadwal snapshot yang dilepas tidak akan dikelola oleh kebijakan baru. Snapshot tersebut akan dipertahankan tanpa batas waktu sampai Anda menghapusnya.

Gunakan konsol Google Cloud, gcloud CLI, atau REST untuk menghapus dan mengganti jadwal snapshot Anda.

Konsol

  1. Di konsol Google Cloud, buka halaman Disk.

    Buka halaman Disk

  2. Pilih disk dengan jadwal yang ingin Anda lepaskan.
  3. Di halaman Manage disk, klik Edit. Anda mungkin perlu mengklik menu More actions terlebih dahulu.
  4. Buka menu drop-down Jadwal snapshot.
  5. Klik Tidak ada jadwal untuk melepaskan jadwal dari disk.
  6. Anda dapat membuat jadwal baru, atau menukar jadwal saat mengedit opsi disk.
  7. Klik Simpan untuk menyelesaikan tugas.

gcloud

  1. Gunakan perintah gcloud disks remove-resource-policies untuk melepaskan jadwal snapshot dari disk dengan jadwal yang ingin Anda ubah.

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

    Ganti kode berikut:

    • DISK_NAME: nama disk dengan jadwal snapshot yang terpasang
    • SCHEDULE_NAME: nama jadwal snapshot yang ingin Anda lepaskan dari disk ini
    • REGION: region tempat jadwal snapshot Anda berada
    • ZONE: zona tempat disk zonal Anda berada
  2. Gunakan perintah gcloud disks add-resource-policies untuk menambahkan jadwal snapshot baru ke disk.

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

    Ganti kode berikut:

    • DISK_NAME: nama disk dengan kebijakan resource jadwal snapshot
    • SCHEDULE_NAME: nama jadwal snapshot yang ingin Anda tambahkan ke disk ini
    • ZONE: zona tempat disk Anda berada

REST

  1. Lepaskan jadwal snapshot saat ini dari disk dengan membuat permintaan POST ke disks.removeResourcePolicies.

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

    Ganti kode berikut:

    • PROJECT_ID: nama project
    • ZONE: zona tempat disk berada
    • DISK_NAME: nama disk dengan jadwal snapshot terkait
    • REGION: lokasi jadwal snapshot
    • SCHEDULE_NAME: nama jadwal snapshot yang Anda hapus dari disk ini
  2. Lampirkan jadwal snapshot baru ke disk dengan membuat permintaan POST ke metode disks.addResourcePolicies.

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

    Ganti kode berikut:

    • PROJECT_ID: nama project
    • ZONE: lokasi disk
    • DISK_NAME: nama disk
    • REGION: lokasi jadwal snapshot
    • SCHEDULE_NAME: nama jadwal snapshot yang Anda terapkan ke disk ini

Hapus jadwal snapshot

Jika Anda menghapus jadwal snapshot, semua snapshot yang dihasilkan secara otomatis terkait jadwal snapshot akan disimpan secara permanen. Namun, setelah dihapus, snapshot tidak dapat dibuat lagi.

Kebijakan retensi Anda adalah bagian dari jadwal snapshot. Setelah jadwal dihapus, kebijakan retensi Anda tidak lagi berlaku. Snapshot yang telah dibuat akan disimpan secara permanen sampai Anda menghapusnya secara manual.

Untuk menghapus jadwal snapshot yang ada, gunakan metode Konsol Google Cloud, Google Cloud CLI, atau Compute Engine API. Jika jadwal sudah terpasang ke disk, lepaskan jadwal dari disk terlebih dahulu, lalu hapus jadwal. Anda tidak dapat menghapus jadwal snapshot yang terpasang pada disk.

Konsol

  1. Di Konsol Google Cloud, buka halaman Snapshot.

    Buka halaman Snapshot

  2. Pilih Jadwal snapshot untuk melihat daftar jadwal Anda.
  3. Pilih jadwal yang tidak terkait dengan disk.
  4. Klik Delete.

gcloud

Untuk menghapus jadwal snapshot, gunakan perintah resource-policies delete.

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

Ganti kode berikut:

  • SCHEDULE_NAME: nama jadwal snapshot
  • REGION: lokasi jadwal snapshot

Go

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

Untuk menghapus jadwal snapshot, buat permintaan DELETE ke metode resourcePolicies.delete. Jika jadwal snapshot sudah terpasang ke disk, Anda akan menerima error.

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

Ganti kode berikut:

  • PROJECT_ID: nama project
  • REGION: lokasi jadwal snapshot
  • SCHEDULE_NAME: nama jadwal snapshot

Logging dan pemantauan

Setiap snapshot terjadwal yang terkait dengan disk terus membuat peristiwa sistem, yang dipantau dan dicatat ke dalam log setiap saat. Log audit peristiwa sistem selalu diaktifkan.

Log ini memberikan informasi perilaku tentang snapshot terjadwal Anda untuk setiap disk terkait. Anda dapat melihat log dari menu Logging di konsol Google Cloud.

Untuk mengetahui informasi selengkapnya tentang cara menggunakan Logs Explorer, lihat Melihat log menggunakan Logs Explorer.

Konsol

  1. Di Konsol Google Cloud, buka halaman Logs Explorer.

    Buka halaman Logs Explorer

  2. Di menu drop-down All resource, arahkan kursor ke Disk, lalu pilih All disk_id.

  3. Di menu drop-down All logs, pilih cloudaudit.googleapis.com/system_event lalu klik OK.

  4. Di menu drop-down Any log level, pilih jenis log.

Langkah berikutnya