ניהול לוחות זמנים של תמונות מצב לדיסקים

במאמר הזה מוסבר איך לנהל את לוחות הזמנים של יצירת תמונות מצב של נפחי Persistent Disk ו-Google Cloud Hyperdisk אזוריים ואזוריים.

אפשר לנהל את לוחות הזמנים של תמונות המצב באופן הבא:

  • הצגת לוחות זמנים של תמונות מצב
  • שינוי לוחות הזמנים של תמונות המצב
  • מחיקת לוחות זמנים של תמונות מצב

אפשר גם להגדיר התראות לגבי תמונות מצב מתוזמנות.

לפני שמתחילים

תפקידים והרשאות נדרשים

כדי לקבל את ההרשאות שדרושות ליצירת לוח זמנים ליצירת תמונת מצב, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

התפקידים המוגדרים מראש האלה כוללים את ההרשאות שנדרשות ליצירת לוח זמנים ליצירת תמונת מצב. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי ליצור תזמון של צילום תמונת מצב, נדרשות ההרשאות הבאות:

  • כדי לראות את לוחות הזמנים של ה-snapshots: compute.resourcePolicies.list בפרויקט או בארגון
  • כדי לעדכן את התזמון של קובץ snapshot:
    • compute.resourcePolicies.update במדיניות המשאבים
    • compute.resourcePolicies.get במדיניות המשאבים
  • כדי להחליף את לוח הזמנים של הצילום:
    • compute.resourcePolicies.use במדיניות המשאבים
    • compute.disks.addResourcePolicies בדיסק
    • compute.disks.removeResourcePolicies בדיסק
  • כדי למחוק תזמון של תמונת מצב:
    • compute.resourcePolicies.delete במדיניות המשאבים
    • compute.disks.removeResourcePolicies בדיסק

יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.

הצגת לוחות זמנים של תמונות מצב

כדי לקבל רשימה של לוחות זמנים ליצירת תמונות מצב, משתמשים במסוף, בפקודה gcloud או במתודה של Compute Engine API. בבקשה הזו מוצגים השם, התיאור והאזור של כל לוחות הזמנים של תמונות המצב בפרויקט.

המסוף

  1. נכנסים לדף Snapshots במסוף Cloud de Confiance .

    לדף Snapshots

  2. לוחצים על הכרטיסייה לוחות זמנים של תמונות מצב.
  3. כדי לצמצם את רשימת לוחות הזמנים של התמונות, משתמשים בשדה Filter.
  4. לוחצים על השם של לוח הזמנים ליצירת תמונת מצב כדי לראות את הפרטים שלו.

gcloud

כדי לראות רשימה של לוחות הזמנים של הצילומים, משתמשים בפקודה resource-policies list.

 gcloud compute resource-policies list

כדי לראות את התיאור של תזמון ספציפי של תמונת מצב, משתמשים בפקודה resource-policies describe.

gcloud compute resource-policies describe SCHEDULE_NAME

מחליפים את SCHEDULE_NAME בשם של תזמון הצילום.

המשך

הצגת רשימה של לוחות זמנים של קובצי 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
}

תיאור של תזמון ליצירת תמונת מצב

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

הצגת רשימה של לוחות זמנים של קובצי 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;
    }
  }
}

תיאור של תזמון ליצירת תמונת מצב

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

הצגת רשימה של לוחות זמנים של קובצי 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

תיאור של תזמון ליצירת תמונת מצב

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

שולחים בקשת GET אל resourcePolicies.aggregatedList כדי לקבל רשימה של לוחות הזמנים של הצילומים של פרויקט.

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

מחליפים את PROJECT_ID בשם הפרויקט.

צפייה בלוחות הזמנים של תמונות המצב לפי אזור

כדי לראות את לוחות הזמנים של יצירת התמונות של פרויקט באזור מסוים, משתמשים במסוףCloud de Confiance , ב-CLI של gcloud או ב-REST.

המסוף

  1. נכנסים לדף Snapshots במסוף Cloud de Confiance .

    לדף Snapshots

  2. לוחצים על הכרטיסייה לוחות זמנים של תמונות מצב.
  3. כדי לראות את לוחות הזמנים של תמונות מצב באזור מסוים, משתמשים בשדה Filter.

gcloud

כדי לראות את לוחות הזמנים של תמונות המצב של פרויקט באזור ספציפי, משתמשים בפקודה resource-policies list.

gcloud compute resource-policies list PROJECT_ID --filter REGION

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: שם הפרויקט
  • REGION: האזור, למשל us-west1

REST

שולחים בקשת GET ל-method‏ resourcePolicies.list כדי לאחזר את לוחות הזמנים של ה-snapshot שנוצרו באזור.

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

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: שם הפרויקט
  • REGION: האזור, למשל us-west1

שינוי של תזמון תמונת מצב

אחרי שיוצרים תזמון של צילום תמונת מצב, אפשר לשנות את השדות הבאים באופן דינמי באמצעות ההליך עדכון תזמון של צילום תמונת מצב:

  • תיאור
  • לוח הזמנים של תמונות המצב
  • תוויות שנוספו לתמונות המצב שנוצרו
  • המדיניות בנושא מחיקת נתונים של דיסק מקור לטיפול בתמונות מצב שנוצרו אוטומטית אם דיסק המקור נמחק
  • מדיניות שימור שקובעת כמה זמן יישמרו תמונות מצב שנוצרו מלוח הזמנים של תמונות המצב

כדי לעדכן ערכים אחרים בלוח זמנים של תמונת מצב, צריך למחוק את לוח הזמנים של תמונת המצב וליצור לוח זמנים חדש, כמו שמתואר במאמר החלפת לוח זמנים של תמונת מצב.

עדכוני לוח הזמנים של תמונות המצב נכנסים לתוקף בתמונת המצב הראשונה אחרי העדכונים. אם תמונת מצב פועלת בזמן שאתם מעדכנים את לוח הזמנים של תמונות המצב, השינויים ייכנסו לתוקף בתמונת המצב הבאה.

עדכון לוח זמנים של תמונת מצב

אתם יכולים להשתמש ב-Google Cloud CLI או ב-Compute Engine API כדי לשנות חלק מהמאפיינים של לוח הזמנים ליצירת תמונות מצב, כמו שמתואר במאמר שינוי לוח זמנים ליצירת תמונות מצב.

כדי לשנות מאפיינים אחרים של לוח הזמנים ליצירת תמונת מצב, משתמשים בשיטה שמתוארת במאמר החלפת לוח זמנים ליצירת תמונת מצב.

המסוף

  1. נכנסים לדף Snapshots במסוף Cloud de Confiance .

    לדף Snapshots

  2. לוחצים על לוחות זמנים של תמונות מצב כדי לראות את רשימת לוחות הזמנים.
  3. לוחצים על השם של תזמון הצילום שרוצים לשנות.
  4. בדף הפרטים של תזמון הצילום, לוחצים על הלחצן עריכת התזמון.

gcloud

כדי לעדכן את התיאור, התזמון, מדיניות השמירה או התוויות של תזמון צילום תמונת מצב, משתמשים בפקודה compute resource-policies update.

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

מחליפים את מה שכתוב בשדות הבאים:

  • SCHEDULE_NAME: השם של לוח הזמנים ליצירת ה-snapshot.
  • REGION: האזור שבו נמצא לוח הזמנים של הצילום.
  • DESCRIPTION: תיאור של לוח הזמנים של ה-snapshot. מוסיפים גרשיים מסביב לתיאור.
  • KEY ו-VALUE: צמד מפתח/ערך שאפשר להשתמש בו כדי לקבץ משאבים קשורים או משאבים שמשויכים זה לזה.
  • DAYS: מספר הימים המקסימלי שקובץ ה-Snapshot נשמר לפני שהוא נמחק.
  • DELETE_OPTION: התנהגות השמירה של קובצי snapshot אוטומטיים אחרי שהדיסק המקורי נמחק. הערך צריך להיות אחד מהערכים הבאים:
    • apply-retention-policy: כשדיסק המקור נמחק, ממשיכים להחיל את חלון השמירה על קובצי snapshot שנוצרו על ידי תזמון ה-snapshot.
    • keep-auto-snapshots: (ברירת מחדל) אם דיסק המקור נמחק, כל קובצי ה-snapshot שנוצרו על ידי תזמון ה-snapshot יישמרו, ללא קשר לחלון השמירה.
  • START_TIME: שעת ההתחלה לפי שעון UTC. השעה חייבת להתחיל בשעה עגולה. לדוגמה:
    • ‫14:00 לפי שעון החוף המערבי (PST) זה 22:00.
    • אם תגדירו שעת התחלה של 22:13, תקבלו הודעת שגיאה.
  • SCHEDULE_FLAG: אחד מהדגלים הבאים:

    • --hourly-schedule=HOURLY_INTERVAL: מספר השעות בין כל קובץ snapshot. הערך HOURLY_INTERVAL חייב להיות מספר שלם בין 1 ל-23. לדוגמה, אם מגדירים את --hourly-schedule ל-12, המשמעות היא שהתמונה תיווצר כל 12 שעות.
    • --daily-schedule: יוצר קובץ snapshot מדי יום בשעה START_TIME
    • --weekly-schedule=WEEKLY_INTERVAL: מגדיר את היום שבו רוצים ליצור את ה-snapshot. צריך לכתוב את שם היום בשבוע במילים, והערכים לא תלויי אותיות רישיות.

    • --weekly-schedule-from-file=FILE_NAME: מציין קובץ שמכיל את לוח הזמנים השבועי של קובצי ה-snapshot. אפשר לציין לוחות זמנים שבועיים לימים שונים בשבוע ובשעות שונות באמצעות קובץ. לדוגמה, יכול להיות שבקובץ שלכם מוגדר לוח זמנים ליצירת תמונת מצב בימים שני ורביעי: none [{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}] אם כוללים שעת התחלה בקובץ, לא צריך להגדיר את הדגל --start-time. בלוח הזמנים נעשה שימוש באזור הזמן UTC. השעה חייבת להתחיל בשעה עגולה. לדוגמה:

      • ‫14:00 לפי שעון החוף המערבי (PST) זה 22:00.
      • אם תגדירו שעת התחלה של 22:13, תקבלו הודעת שגיאה.

    הדגלים של תדירות יצירת ה-snapshot‏ hourly-schedule, ‏daily-schedule, ‏weekly-schedule ו-weekly-schedule-from-file הם בלעדיים. אפשר להשתמש רק באחד מהם ללוח הזמנים של הצילום.

לדוגמה:

כדי לשנות את התזמון של תמונת מצב לתזמון יומי:

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

כדי לשנות את תמונת המצב לתזמון שעתי, וגם לעדכן את התיאור ואת התווית של תמונת המצב:

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"

כדי לשנות את מדיניות שמירת הנתונים של תמונת מצב ואת מדיניות המחיקה של דיסק המקור עבור תזמון של תמונות מצב:

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

המשך

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

יוצרים בקשת PATCH ל-resourcePolicies method כדי לעדכן את התיאור, התזמון, מדיניות שמירת הנתונים, המדיניות בנושא מחיקת נתונים של דיסק המקור או התוויות של תזמון הצילום. בגוף הבקשה צריך לציין רק את name ואת השדות שרוצים לעדכן.

  • משנים את התיאור והתווית:

    PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME
    {
        "name": "SCHEDULE_NAME",
        "description": "DESCRIPTION",
        "snapshotProperties": {
            "labels": {"KEY": "VALUE"}
        }
    }
    
  • כדי לשנות את התזמון של תמונת המצב לשעתי:

    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
               }
            }
        }
    }
    
  • כדי לשנות את התזמון של תמונת המצב ליומי:

    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
               }
            }
        }
    }
    
  • כדי לשנות את לוח הזמנים של התמונות למצב שבועי:

    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
                     }
                  ]
               }
            }
        }
    }
    
  • שינוי מדיניות השמירה של התמונות:

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

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: שם הפרויקט.
  • REGION: האזור שבו נמצאת תוכנית ה-snapshot.
  • SCHEDULE_NAME: השם של לוח הזמנים ליצירת ה-snapshot.
  • DESCRIPTION: תיאור של לוח הזמנים של ה-snapshot. מוסיפים גרשיים מסביב לתיאור.
  • KEY ו-VALUE: צמד מפתח/ערך שאפשר להשתמש בו כדי לקבץ משאבים קשורים או משויכים.
  • HOURLY_INTERVAL: הגדרה של המרווח שבו רוצים ליצור snapshot. מגדירים את לוח הזמנים השעתי באמצעות מספר שלם בין 1 ל-23. כדי שהתמונות ייווצרו באותה שעה בכל יום, בוחרים מספר שמתחלק ב-24 ללא שארית (1, 2, 3, 4, 6, 8 או 12). לדוגמה, אם מגדירים את --hourly-schedule ל-12, המשמעות היא שקובץ ה-snapshot נוצר כל 12 שעות.
  • DAILY_INTERVAL: מגדיר את מספר הימים בין כל קובץ snapshot. כדי ליצור snapshot כל יום, משתמשים בערך 1.
  • WEEKLY_INTERVAL: מגדיר לוח זמנים שפועל בימים ספציפיים בשבוע. מציינים יום אחד או יותר. אלה האפשרויות הזמינות: MONDAY,‏ TUESDAY,‏ WEDNESDAY,‏ THURSDAY,‏ FRIDAY,‏ SATURDAY ו-SUNDAY. צריך לכתוב את שמות הימים בשבוע במילים, ולא באותיות רישיות. אפשר להגדיר עד 7 מרווחי זמן ל-dayOfWeeks, אחד לכל יום בשבוע.
  • START_TIME: שעת ההתחלה לפי שעון UTC. השעה חייבת להתחיל בשעה עגולה. לדוגמה:
    • ‫14:00 לפי שעון החוף המערבי (PST) זה 22:00 UTC.
    • אם תגדירו שעת התחלה של 22:13, תקבלו הודעת שגיאה.
  • DAYS: מספר הימים המקסימלי שקובץ ה-Snapshot נשמר לפני שהוא נמחק.
  • DELETE_OPTION: התנהגות השמירה של קובצי snapshot אוטומטיים אחרי שהדיסק המקורי נמחק. הערך צריך להיות אחד מהערכים הבאים:
    • APPLY_RETENTION_POLICY: כשדיסק המקור נמחק, ממשיכים להחיל את חלון השמירה על קובצי snapshot שנוצרו על ידי לוח הזמנים של קובצי ה-snapshot.
    • KEEP_AUTO_SNAPSHOTS: (ברירת מחדל) אם דיסק המקור נמחק, כל קובצי ה-snapshot שנוצרו על ידי תזמון ה-snapshot יישמרו, ללא קשר לחלון השמירה.

החלפת אירוע לתזמון של תמונת מצב

כדי למחוק את לוח הזמנים של הצילום וליצור לוח זמנים חדש, פועלים לפי השלבים הבאים. משתמשים בשיטה הזו כדי לשנות מאפיינים של תזמון צילום תמונת מצב שלא ניתן לשנות באמצעות התהליך עדכון תזמון צילום תמונת מצב.

אם אתם מחליפים תזמון של תמונת מצב שכבר מצורף לדיסק, אתם צריכים קודם לנתק את התזמון מהדיסק ולמחוק אותו. אחר כך תוכלו ליצור לוח זמנים חדש ולצרף אותו לדיסק.

קובצי snapshot שנוצרו מלוח הזמנים של קובצי ה-snapshot המנותקים לא ינוהלו על ידי המדיניות החדשה. קובצי ה-snapshot האלה יישמרו ללא הגבלת זמן עד שתמחקו אותם.

משתמשים במסוף Cloud de Confiance , ב-CLI של gcloud או ב-REST כדי להסיר את לוח הזמנים של יצירת התמונות ולהחליף אותו.

המסוף

  1. נכנסים לדף Disks במסוף Cloud de Confiance .

    לדף Disks

  2. בוחרים את הדיסק שכולל את התזמון שרוצים לנתק.
  3. בדף Manage disk (ניהול הדיסק), לוחצים על Edit (עריכה). יכול להיות שתצטרכו ללחוץ קודם על התפריט פעולות נוספות.
  4. פותחים את התפריט הנפתח תזמון הצילום.
  5. לוחצים על No schedule (ללא תזמון) כדי לבטל את השיוך של התזמון לדיסק.
  6. אפשר ליצור לוח זמנים חדש או להחליף את לוח הזמנים בזמן עריכת האפשרויות של הדיסק.
  7. לוחצים על שמירה כדי להשלים את המשימה.

gcloud

  1. משתמשים בפקודה gcloud compute disks remove-resource-policies כדי לנתק את לוח הזמנים של התמונות מכונן הדיסק עם לוח הזמנים שרוצים לשנות.

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

    מחליפים את מה שכתוב בשדות הבאים:

    • DISK_NAME: השם של הדיסק שאליו מחובר לוח הזמנים של ה-snapshot
    • SCHEDULE_NAME: השם של תזמון ה-snapshot שרוצים לנתק מהדיסק הזה
    • REGION: האזור שבו נמצאת תוכנית ה-snapshot
    • ZONE: האזור שבו נמצא הדיסק האזורי
  2. משתמשים בפקודה gcloud compute disks add-resource-policies כדי להוסיף את לוח הזמנים החדש ליצירת תמונת מצב לדיסק.

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

    מחליפים את מה שכתוב בשדות הבאים:

    • DISK_NAME: השם של הדיסק עם מדיניות המשאבים של לוח הזמנים ליצירת ה-snapshot
    • SCHEDULE_NAME: השם של תזמון ה-Snapshot שרוצים להוסיף לדיסק הזה
    • ZONE: האזור שבו הדיסק נמצא

REST

  1. כדי לנתק את התזמון הנוכחי של יצירת ה-snapshot מדיסק, צריך ליצור בקשת POST אל disks.removeResourcePolicies.

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

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: שם הפרויקט
    • ZONE: האזור שבו נמצא הדיסק
    • DISK_NAME: השם של הדיסק עם לוח הזמנים המשויך ליצירת ה-snapshot
    • REGION: המיקום של לוח הזמנים ליצירת תמונות מצב
    • SCHEDULE_NAME: השם של תזמון ה-snapshot שאתם מסירים מהדיסק הזה
  2. כדי לצרף את לוח הזמנים החדש ליצירת snapshot לדיסק, יוצרים בקשת POST אל ה-method‏ disks.addResourcePolicies.

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

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: שם הפרויקט
    • ZONE: המיקום של הדיסק
    • DISK_NAME: שם הדיסק
    • REGION: המיקום של לוח הזמנים ליצירת תמונות מצב
    • SCHEDULE_NAME: השם של תזמון ה-snapshot שאתם מחילים על הדיסק הזה

מחיקה של לוח זמנים ליצירת תמונת מצב

אם מוחקים לוח זמנים ליצירת תמונות מצב, כל תמונות המצב שנוצרו אוטומטית ומשויכות ללוח הזמנים הזה נשמרות באופן סופי. אבל אחרי שמוחקים את התזמון, אי אפשר יותר ליצור תמונות מצב.

מדיניות שמירת הנתונים היא חלק מלוח הזמנים של הצילום. אחרי שמוחקים את התזמון, מדיניות שמירת הנתונים לא חלה יותר. תמונות מצב שכבר נוצרו נשמרות באופן קבוע עד שמוחקים אותן באופן ידני.

כדי למחוק תזמון קיים של צילום מצב, משתמשים בשיטהCloud de Confiance של מסוף Google Cloud,‏ Google Cloud CLI או Compute Engine API. אם לוח הזמנים כבר מצורף לדיסק, קודם מבטלים את הצירוף של לוח הזמנים לדיסק ואז מוחקים את לוח הזמנים. אי אפשר למחוק לוח זמנים של תמונת מצב שמצורף לדיסק.

המסוף

  1. נכנסים לדף Snapshots במסוף Cloud de Confiance .

    לדף Snapshots

  2. לוחצים על לוחות זמנים של תמונות מצב כדי לראות את רשימת לוחות הזמנים.
  3. בוחרים לוח זמנים שלא משויך לדיסק.
  4. לוחצים על מחיקה.

gcloud

כדי למחוק לוח זמנים ליצירת תמונת מצב, משתמשים בפקודה resource-policies delete.

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

מחליפים את מה שכתוב בשדות הבאים:

  • SCHEDULE_NAME: השם של לוח הזמנים ליצירת ה-snapshot
  • REGION: המיקום של לוח הזמנים ליצירת תמונות מצב

המשך

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

כדי למחוק לוח זמנים של תמונת מצב, שולחים בקשת DELETE ל-method‏ resourcePolicies.delete. אם לוח הזמנים של יצירת התמונות כבר מצורף לדיסק, תוצג שגיאה.

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

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: שם הפרויקט
  • REGION: המיקום של לוח הזמנים ליצירת תמונות מצב
  • SCHEDULE_NAME: השם של לוח הזמנים ליצירת ה-snapshot

רישום ביומן ומעקב

כל תמונת מצב מתוזמנת שמשויכת לדיסק יוצרת באופן רציף אירוע מערכת, שמנוטר ומתועד בכל רגע. יומני הביקורת System Event תמיד מופעלים.

היומנים האלה מספקים מידע על ההתנהגות של התמונות המתוזמנות של כל דיסק משויך. אפשר לראות את היומנים בתפריט Logging במסוף Cloud de Confiance .

מידע נוסף על השימוש ב-Logs Explorer מופיע במאמר הצגת יומנים באמצעות Logs Explorer.

המסוף

  1. נכנסים לדף Logs Explorer במסוף Cloud de Confiance .

    כניסה לדף Logs Explorer

  2. ברשימה הנפתחת All resource, מצביעים על Disk ובוחרים באפשרות All disk_id.

  3. ברשימה הנפתחת All logs, בוחרים באפשרות cloudaudit.googleapis.com/system_event ולוחצים על OK.

  4. ברשימה הנפתחת Any log level, בוחרים את סוג היומן.

המאמרים הבאים