API を使用してアラート ポリシーを作成する

アラート ポリシーは、Cloud Monitoring API で AlertPolicy オブジェクトとして表されます。このオブジェクトは、システムにおける異常な状態の可能性を示す一連の条件を記述するものです。

このドキュメントの内容は次のとおりです。

  • Monitoring API のアラート ポリシーの表現方法。
  • アラート ポリシーのために Monitoring API が提供している条件のタイプ。
  • Google Cloud CLI またはクライアント ライブラリを使用してアラート ポリシーを作成する方法。

アラート ポリシーの構造

AlertPolicy 構造は、アラート ポリシーのコンポーネントを定義します。ポリシーを作成するときは、次の AlertPolicy フィールドの値を指定します。

  • displayName: ポリシーの説明ラベル。
  • documentation: 対応者に役立つ情報。 このフィールドは省略可能です。documentation オブジェクトには次のものが含まれます。
    • content: 通知の本文に表示されるユーザー定義のテキスト。
    • subject: 通知の件名。件名は 255 文字以内にしてください。
  • userLabels: ポリシーに付けられたユーザー定義のラベル。アラートでラベルを使用する方法については、ラベルでアラートにアノテーションを付けるをご覧ください。
  • conditions[]: Condition 構造の配列。
  • combiner: 複数の条件の処理方法を決定する論理演算子。
  • notificationChannels[]: リソース名の配列。それぞれが NotificationChannel を識別します。
  • alertStrategy: データが到着しなくなったときに Monitoring がインシデントを閉じるまでの時間を指定します。このオブジェクトでは、指標ベースのアラートで繰り返し通知を有効にするかどうか、および、通知の間隔も指定します。詳細については、繰り返し通知を送信するをご覧ください。

Cloud Monitoring API と Google Cloud コンソールを使用するときに、severity フィールドを指定することもできます。このフィールドを使用して、インシデントの重大度を定義できます。重大度を指定しない場合、Cloud Monitoring はアラート ポリシーの重大度を No Severity に設定します。

作成した条件によっては、他にも使用できるフィールドがある場合があります。

アラート ポリシーに 1 つの条件が含まれている場合、その条件が満たされたときに通知が送信されます。アラート ポリシーに複数の条件が含まれている場合の通知については、複数の条件を持つポリシーポリシーあたりの通知数をご覧ください。

アラート ポリシーを作成または変更すると、Monitoring によって name フィールドを含む他のフィールドも設定されます。name フィールドの値は、ポリシーを識別するアラート ポリシーのリソース名です。リソース名の形式は次のとおりです。

projects/PROJECT_ID/alertPolicies/POLICY_ID

API の条件のタイプ

Cloud Monitoring API は、Condition 構造でさまざまな条件タイプをサポートしています。指標ベースのアラート ポリシーには複数の条件タイプがあり、ログベースのアラート ポリシーには 1 つの条件タイプがあります。以降のセクションでは、使用可能な条件の種類について説明します。

指標ベースのアラート ポリシーの条件

ログベースの指標を含む指標データをモニタリングするアラート ポリシーを作成するには、次の条件タイプを使用します。

フィルタベースの指標の条件

MetricAbsence 条件と MetricThreshold 条件では、Monitoring フィルタを使用して、モニタリングする時系列データを選択します。条件構造の他のフィールドでは、データをフィルタリング、グループ化、集計する方法を指定します。これらのコンセプトの詳細については、フィルタリングと集計: 時系列の操作をご覧ください。

MetricAbsence 条件タイプを使用する場合は、すべての時系列が不在の場合にのみ満たす条件を作成できます。この条件では、aggregations パラメータを使用して複数の時系列を 1 つの時系列に集計します。詳細については、API ドキュメントの MetricAbsence リファレンスをご覧ください。

指標の不在のアラート ポリシーでは、一部のデータがすでに書き込まれている必要があります。詳細については、指標の不在のアラート ポリシーを作成するをご覧ください。

予測値に基づいて通知を受け取る場合は、MetricThreshold 条件タイプを使用して forecastOptions フィールドを設定するようにアラート ポリシーを構成します。このフィールドが設定されていない場合、測定データがしきい値と比較されます。ただし、このフィールドが設定されていると、予測データがしきい値と比較されます。詳細については、予測指標値のアラート ポリシーを作成するをご覧ください。

MQL ベースの指標の条件

MonitoringQueryLanguageCondition 条件は、Monitoring Query Language(MQL)を使用して、モニタリングする時系列データを選択し、操作します。しきい値と値を比較するアラート ポリシーを作成したり、この条件タイプで値が存在しない場合をテストしたりできます。MonitoringQueryLanguageCondition 条件を使用する場合は、アラート ポリシーで唯一の条件である必要があります。詳細については、MQL のアラート ポリシーをご覧ください。

PromQL ベースの指標の条件

PrometheusQueryLanguageCondition 条件では、Prometheus Query Language(PromQL)クエリを使用して、モニタリングする時系列データを選択し操作します。単純なクエリも複雑なクエリも作成し、動的しきい値、比率、指標比較などのクエリ構造を使用できます。

PrometheusQueryLanguageCondition 条件を使用する場合は、アラート ポリシーで唯一の条件である必要があります。詳細については、PromQL のアラート ポリシーをご覧ください。

比率に関するアラートの条件

指標しきい値のアラート ポリシーを作成して、2 つの指標の比率をモニタリングできます。これらのポリシーは、MetricThreshold または MonitoringQueryLanguageCondition の条件タイプを使用して作成できます。 また、Google Cloud コンソールで MQL を直接使用することもできます。しきい値条件を作成するためのグラフィカル インターフェースを使用して、比率ベースの条件を作成または管理することはできません。

MQL を使用して比率ベースのアラート ポリシーを作成することをおすすめします。MQL では、MetricTheshold 条件タイプと Monitoring フィルタを使用して作成できるよりも強力で柔軟なクエリを構築できます。 たとえば、MonitoringQueryLanguageCondition 条件を使用すると、ゲージ指標とデルタ指標の比率を計算できます。例については、MQL アラート ポリシーの例をご覧ください。

MetricThreshold 条件を使用する場合、比率の分子と分母は同じ MetricKind である必要があります。指標とそのプロパティのリストについては、指標リストをご覧ください。

一般に、ラベル値を使用して、単一の指標タイプに対して収集された時系列に基づいて比率を計算することが最適です。2 つの異なる指標タイプで計算された比率は、サンプリング期間とアライメント ウィンドウが異なるため、異常が発生する可能性があります。

たとえば、RPC の合計数と RPC のエラー数の 2 つの異なる指標タイプがあり、RPC の合計数に対する RPC のエラー数の割合を計算するとします。失敗した RPC は、両方の指標タイプの時系列でカウントされます。そのため、時系列をアライメントすると、失敗した RPC が両方の時系列の同じアライメント間隔に表示されない場合があります。この差は、次のような原因で発生することがあります。

  • 同じイベントを記録する 2 つの異なる時系列があるため、コレクションを実装する 2 つの基になるカウンタ値があり、それらはアトミックに更新されません。
  • サンプリング レートは異なる場合があります。時系列が共通の期間にアラインメントされると、単一のイベントのカウントが、異なる指標の時系列の隣接するアラインメント間隔に表示される場合があります。

対応するアライメント間隔の値の数の差は、1/0 や 2/1 などの意味のない error/total 比率値になる場合があります。

大きな数値の比率の場合、意味のない値になる可能性は低くなります。 サンプリング期間よりも長いアライメント ウィンドウを使用するか、特定のラベルのデータをグループ化すれば、集計で大きな数値を取得できます。これらの手法は、特定の間隔でのポイント数のわずかな違いによる影響を最小限に抑えます。つまり、間隔内の予想されるポイント数が 3 の場合、予想される数が 300 の場合よりも、2 ポイントの不一致による影響が大きくなります。

組み込みの指標タイプを使用している場合は、指標タイプ全体の比率を計算して、必要な値を取得せざるを得ない場合があります。

2 つの異なる指標で同じもの(エラー ステータスを返す RPC など)をカウントする可能性のあるカスタム指標を設計している場合は、代わりに、各カウントを 1 回だけ含む単一の指標を検討してください。たとえば、RPC をカウントしていて、すべての RPC に対する失敗した RPC の比率を追跡するとします。RPC をカウントする単一の指標タイプを作成し、ラベルを使用して「OK」ステータスを含む呼び出しのステータスを記録します。次に、その場合の単一のカウンタを更新することにより、各ステータス値、エラーまたは「OK」が記録されます。

ログベースのアラート ポリシーの条件

フィルタに一致するメッセージがログエントリに表示されたときに通知するログベースのアラート ポリシーを作成するには、LogMatch 条件タイプを使用します。LogMatch 条件を使用する場合は、それがアラート ポリシーの唯一の条件である必要があります。

LogMatch 条件タイプをログベースの指標と一緒に使用しないでください。ログベースの指標をモニタリングするアラート ポリシーは、指標ベースのポリシーです。ログベースの指標またはログエントリをモニタリングするアラート ポリシーの選択方法について詳しくは、ログのモニタリングをご覧ください。

API によるアラート ポリシーの管理のドキュメントの例で使用されているアラート ポリシーは、指標ベースのアラート ポリシーです。ただし、原則はログベースのアラート ポリシーと同じです。ログベースのアラート ポリシーの詳細については、Cloud Logging ドキュメントの Monitoring API を使用してログベースのアラートを作成するをご覧ください。

始める前に

API に対してコードを記述する前に以下が必要です。

  • アラート ポリシーで使用される一般的なコンセプトと用語を十分理解する。詳細については、アラートの概要をご覧ください。
  • Cloud Monitoring API が使用可能である。詳細については、API の有効化をご覧ください。
  • クライアント ライブラリを使用する場合は、使用する言語のライブラリをインストールする。詳しくは、クライアント ライブラリをご覧ください。 現在、アラートの API サポートは、C#、Go、Java、Node.js、および Python でのみ使用できます。
  • Google Cloud CLI を使用する場合は、インストールする。ただし、Cloud Shell を使用する場合は、Google Cloud CLI がすでにインストールされていること。

    gcloud インターフェースを使用した例もここで説明します。gcloud の例ではすべて、現在のプロジェクトがターゲット(gcloud config set project [PROJECT_ID])としてすでに設定されているため、呼び出しによって明示的な --project フラグが省略されることが想定されています。サンプル内の現在のプロジェクトの ID は a-gcp-project です。

  • Cloud Monitoring API を使用してアラート ポリシーを作成および変更するために必要な権限を取得するには、プロジェクトに対する Monitoring AlertPolicy 編集者roles/monitoring.alertPolicyEditor)の IAM ロールの付与を管理者に依頼してください。 ロールの付与の詳細については、アクセスの管理をご覧ください。

    必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

    Monitoring の IAM ロールの詳細については、Identity and Access Management を使用してアクセスを制御するをご覧ください。

  • アプリケーションを Google Cloud プロジェクト内のアラート ポリシーの状態を変更するシングル スレッドの Cloud Monitoring API 呼び出しに設計します。たとえば、アラート ポリシーの作成、更新、削除を行うシングル スレッド API 呼び出しなどです。

アラート ポリシーを作成する

プロジェクトでアラート ポリシーを作成するには、alertPolicies.create メソッドを使用します。このメソッドを呼び出す方法、パラメータ、レスポンス データについては、リファレンス ページ alertPolicies.create をご覧ください。

JSON ファイルまたは YAML ファイルからポリシーを作成できます。Google Cloud CLI では、これらのファイルを引数として指定できます。プログラムで JSON ファイルを読み取り、AlertPolicy オブジェクトに変換して、そのオブジェクトから alertPolicies.create メソッドでポリシーを作成することもできます。 アラートルールを含む Prometheus JSON または YAML 構成ファイルがある場合は、gcloud CLI を使用して、PromQL 条件で Cloud Monitoring アラート ポリシーに移行できます。詳細については、Prometheus からのアラートルールとレシーバーの移行をご覧ください。

各アラート ポリシーは、指標スコープのスコープ プロジェクトに属しています。各プロジェクトには最大 500 個のポリシーを含めることができます。API 呼び出しの場合は、「プロジェクト ID」を指定する必要があり、指標スコープのスコープ プロジェクトの ID を値として使用します。この例では、指標スコープのスコープ プロジェクトの ID は a-gcp-project です。

次のサンプルは、アラート ポリシーの作成方法を示していますが、アラート ポリシーを記述する JSON または YAML ファイルの作成方法については説明しません。このサンプルでは、JSON 形式のファイルが存在し、API 呼び出しの発行方法を示しています。JSON ファイルの例については、サンプル ポリシーをご覧ください。指標のモニタリング率に関する一般的な情報については、指標の比率をご覧ください。

gcloud

プロジェクトでアラート ポリシーを作成するには、gcloud alpha monitoring policies create コマンドを使用します。次の例では、rising-cpu-usage.json ファイルから a-gcp-project でアラート ポリシーを作成します。

gcloud alpha monitoring policies create --policy-from-file="rising-cpu-usage.json"

このコマンドが成功すると、新しいポリシーの名前が戻ります。次に例を示します。

Created alert policy [projects/a-gcp-project/alertPolicies/12669073143329903307].

ファイル rising-cpu-usage.json には、表示名「High CPU rate of change」のポリシーの JSON が含まれています。このポリシーの詳細については、変化率ポリシーをご覧ください。

詳細については、gcloud alpha monitoring policies create のリファレンスをご覧ください。

C#

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

static void RestorePolicies(string projectId, string filePath)
{
    var policyClient = AlertPolicyServiceClient.Create();
    var channelClient = NotificationChannelServiceClient.Create();
    List<Exception> exceptions = new List<Exception>();
    var backup = JsonConvert.DeserializeObject<BackupRecord>(
        File.ReadAllText(filePath), new ProtoMessageConverter());
    var projectName = new ProjectName(projectId);
    bool isSameProject = projectId == backup.ProjectId;
    // When a channel is recreated, rather than updated, it will get
    // a new name.  We have to update the AlertPolicy with the new
    // name.  Track the names in this map.
    var channelNameMap = new Dictionary<string, string>();
    foreach (NotificationChannel channel in backup.Channels)
    {
    }
    foreach (AlertPolicy policy in backup.Policies)
    {
        string policyName = policy.Name;
        // These two fields cannot be set directly, so clear them.
        policy.CreationRecord = null;
        policy.MutationRecord = null;
        // Update channel names if the channel was recreated with
        // another name.
        for (int i = 0; i < policy.NotificationChannels.Count; ++i)
        {
            if (channelNameMap.ContainsKey(policy.NotificationChannels[i]))
            {
                policy.NotificationChannels[i] =
                    channelNameMap[policy.NotificationChannels[i]];
            }
        }
        try
        {
            Console.WriteLine("Updating policy.\n{0}",
                policy.DisplayName);
            bool updated = false;
            if (isSameProject)
                try
                {
                    policyClient.UpdateAlertPolicy(null, policy);
                    updated = true;
                }
                catch (Grpc.Core.RpcException e)
                when (e.Status.StatusCode == StatusCode.NotFound)
                { }
            if (!updated)
            {
                // The policy no longer exists.  Recreate it.
                policy.Name = null;
                foreach (var condition in policy.Conditions)
                {
                    condition.Name = null;
                }
                policyClient.CreateAlertPolicy(projectName, policy);
            }
            Console.WriteLine("Restored {0}.", policyName);
        }
        catch (Exception e)
        {
            // If one failed, continue trying to update the others.
            exceptions.Add(e);
        }
    }
    if (exceptions.Count > 0)
    {
        throw new AggregateException(exceptions);
    }
}

Go

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


// restorePolicies updates the project with the alert policies and
// notification channels in r.
func restorePolicies(w io.Writer, projectID string, r io.Reader) error {
	b := backup{}
	if err := json.NewDecoder(r).Decode(&b); err != nil {
		return err
	}
	sameProject := projectID == b.ProjectID

	ctx := context.Background()

	alertClient, err := monitoring.NewAlertPolicyClient(ctx)
	if err != nil {
		return err
	}
	defer alertClient.Close()
	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}
	defer channelClient.Close()

	// When a channel is recreated, rather than updated, it will get
	// a new name.  We have to update the AlertPolicy with the new
	// name.  channelNames keeps track of the new names.
	channelNames := make(map[string]string)
	for _, c := range b.Channels {
		fmt.Fprintf(w, "Updating channel %q\n", c.GetDisplayName())
		c.VerificationStatus = monitoringpb.NotificationChannel_VERIFICATION_STATUS_UNSPECIFIED
		updated := false
		if sameProject {
			req := &monitoringpb.UpdateNotificationChannelRequest{
				NotificationChannel: c.NotificationChannel,
			}
			_, err := channelClient.UpdateNotificationChannel(ctx, req)
			if err == nil {
				updated = true
			}
		}
		if !updated {
			req := &monitoringpb.CreateNotificationChannelRequest{
				Name:                "projects/" + projectID,
				NotificationChannel: c.NotificationChannel,
			}
			oldName := c.GetName()
			c.Name = ""
			newC, err := channelClient.CreateNotificationChannel(ctx, req)
			if err != nil {
				return err
			}
			channelNames[oldName] = newC.GetName()
		}
	}

	for _, policy := range b.AlertPolicies {
		fmt.Fprintf(w, "Updating alert %q\n", policy.GetDisplayName())
		policy.CreationRecord = nil
		policy.MutationRecord = nil
		for i, aChannel := range policy.GetNotificationChannels() {
			if c, ok := channelNames[aChannel]; ok {
				policy.NotificationChannels[i] = c
			}
		}
		updated := false
		if sameProject {
			req := &monitoringpb.UpdateAlertPolicyRequest{
				AlertPolicy: policy.AlertPolicy,
			}
			_, err := alertClient.UpdateAlertPolicy(ctx, req)
			if err == nil {
				updated = true
			}
		}
		if !updated {
			req := &monitoringpb.CreateAlertPolicyRequest{
				Name:        "projects/" + projectID,
				AlertPolicy: policy.AlertPolicy,
			}
			if _, err = alertClient.CreateAlertPolicy(ctx, req); err != nil {
				log.Fatal(err)
			}
		}
	}
	fmt.Fprintf(w, "Successfully restored alerts.")
	return nil
}

Java

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

private static void restoreRevisedPolicies(
    String projectId, boolean isSameProject, List<AlertPolicy> policies) throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    for (AlertPolicy policy : policies) {
      if (!isSameProject) {
        policy = client.createAlertPolicy(ProjectName.of(projectId), policy);
      } else {
        try {
          client.updateAlertPolicy(null, policy);
        } catch (Exception e) {
          policy =
              client.createAlertPolicy(
                  ProjectName.of(projectId), policy.toBuilder().clearName().build());
        }
      }
      System.out.println(String.format("Restored %s", policy.getName()));
    }
  }
}

Node.js

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

const fs = require('fs');

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.AlertPolicyServiceClient();

async function restorePolicies() {
  // Note: The policies are restored one at a time due to limitations in
  // the API. Otherwise, you may receive a 'service unavailable'  error
  // while trying to create multiple alerts simultaneously.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  console.log('Loading policies from ./policies_backup.json');
  const fileContent = fs.readFileSync('./policies_backup.json', 'utf-8');
  const policies = JSON.parse(fileContent);

  for (const index in policies) {
    // Restore each policy one at a time
    let policy = policies[index];
    if (await doesAlertPolicyExist(policy.name)) {
      policy = await client.updateAlertPolicy({
        alertPolicy: policy,
      });
    } else {
      // Clear away output-only fields
      delete policy.name;
      delete policy.creationRecord;
      delete policy.mutationRecord;
      policy.conditions.forEach(condition => delete condition.name);

      policy = await client.createAlertPolicy({
        name: client.projectPath(projectId),
        alertPolicy: policy,
      });
    }

    console.log(`Restored ${policy[0].name}.`);
  }
  async function doesAlertPolicyExist(name) {
    try {
      const [policy] = await client.getAlertPolicy({
        name,
      });
      return policy ? true : false;
    } catch (err) {
      if (err && err.code === 5) {
        // Error code 5 comes from the google.rpc.code.NOT_FOUND protobuf
        return false;
      }
      throw err;
    }
  }
}
restorePolicies();

PHP

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition\MetricThreshold;
use Google\Cloud\Monitoring\V3\AlertPolicy\ConditionCombinerType;
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\ComparisonType;
use Google\Cloud\Monitoring\V3\CreateAlertPolicyRequest;
use Google\Protobuf\Duration;

/**
 * @param string $projectId Your project ID
 */
function alert_create_policy($projectId)
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;

    $policy = new AlertPolicy();
    $policy->setDisplayName('Test Alert Policy');
    $policy->setCombiner(ConditionCombinerType::PBOR);
    /** @see https://cloud.google.com/monitoring/api/resources for a list of resource.type */
    /** @see https://cloud.google.com/monitoring/api/metrics_gcp for a list of metric.type */
    $policy->setConditions([new Condition([
        'display_name' => 'condition-1',
        'condition_threshold' => new MetricThreshold([
            'filter' => 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
            'duration' => new Duration(['seconds' => '60']),
            'comparison' => ComparisonType::COMPARISON_LT,
        ])
    ])]);
    $createAlertPolicyRequest = (new CreateAlertPolicyRequest())
        ->setName($projectName)
        ->setAlertPolicy($policy);

    $policy = $alertClient->createAlertPolicy($createAlertPolicyRequest);
    printf('Created alert policy %s' . PHP_EOL, $policy->getName());
}

Python

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

def restore(project_name, backup_filename):
    """Restore alert policies in a project.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
        backup_filename (str): Name of the file (along with its path) from
            which the alert policies will be restored.
    """
    print(
        "Loading alert policies and notification channels from {}.".format(
            backup_filename
        )
    )
    record = json.load(open(backup_filename, "rt"))
    is_same_project = project_name == record["project_name"]
    # Convert dicts to AlertPolicies.
    policies_json = [json.dumps(policy) for policy in record["policies"]]
    policies = [
        monitoring_v3.AlertPolicy.from_json(policy_json)
        for policy_json in policies_json
    ]
    # Convert dicts to NotificationChannels
    channels_json = [json.dumps(channel) for channel in record["channels"]]
    channels = [
        monitoring_v3.NotificationChannel.from_json(channel_json)
        for channel_json in channels_json
    ]

    # Restore the channels.
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    channel_name_map = {}

    for channel in channels:
        updated = False
        print("Updating channel", channel.display_name)
        # This field is immutable and it is illegal to specify a
        # non-default value (UNVERIFIED or VERIFIED) in the
        # Create() or Update() operations.
        channel.verification_status = (
            monitoring_v3.NotificationChannel.VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED
        )

        if is_same_project:
            try:
                channel_client.update_notification_channel(notification_channel=channel)
                updated = True
            except google.api_core.exceptions.NotFound:
                pass  # The channel was deleted.  Create it below.

        if not updated:
            # The channel no longer exists.  Recreate it.
            old_name = channel.name
            del channel.name
            new_channel = channel_client.create_notification_channel(
                name=project_name, notification_channel=channel
            )
            channel_name_map[old_name] = new_channel.name

    # Restore the alerts
    alert_client = monitoring_v3.AlertPolicyServiceClient()

    for policy in policies:
        print("Updating policy", policy.display_name)
        # These two fields cannot be set directly, so clear them.
        del policy.creation_record
        del policy.mutation_record

        # Update old channel names with new channel names.
        for i, channel in enumerate(policy.notification_channels):
            new_channel = channel_name_map.get(channel)
            if new_channel:
                policy.notification_channels[i] = new_channel

        updated = False

        if is_same_project:
            try:
                alert_client.update_alert_policy(alert_policy=policy)
                updated = True
            except google.api_core.exceptions.NotFound:
                pass  # The policy was deleted.  Create it below.
            except google.api_core.exceptions.InvalidArgument:
                # Annoying that API throws InvalidArgument when the policy
                # does not exist.  Seems like it should throw NotFound.
                pass  # The policy was deleted.  Create it below.

        if not updated:
            # The policy no longer exists.  Recreate it.
            old_name = policy.name
            del policy.name
            for condition in policy.conditions:
                del condition.name
            policy = alert_client.create_alert_policy(
                name=project_name, alert_policy=policy
            )
        print("Updated", policy.name)

作成された AlertPolicy オブジェクトには、追加のフィールドがあります。ポリシー自体には、namecreationRecordmutationRecord の各フィールドがあります。さらに、ポリシーの各条件にも name が付けられます。これらのフィールドは外部で変更することはできないため、ポリシーを作成するときにこれらのフィールドを設定する必要はありません。ポリシーの作成に使用する JSON のどの例にも、これらのフィールドは含まれていません。ただし、フィールドから作成されたポリシーが作成後に取得された場合、フィールドが表示されます。

次のステップ