Benachrichtigungskanäle nach API erstellen und verwalten

In diesem Dokument wird beschrieben, wie Sie Benachrichtigungskanäle mithilfe von Clientbibliotheken oder der Google Cloud CLI erstellen und verwalten, die beide die Cloud Monitoring API aufrufen. Cloud Monitoring verwendet Benachrichtigungskanäle, um Sie oder Ihr Team auf Abruf zu benachrichtigen, wenn eine Benachrichtigungsrichtlinie ausgelöst wird. Es gibt mehrere verfügbare Kanaltypen. Jeder Typ wird in einem Benachrichtigungskanal-Deskriptor beschrieben. Ein Benachrichtigungskanal eines bestimmten Typs ist eine Instanz des Deskriptors für diesen Typ. Ihre Benachrichtigungsrichtlinien enthalten Verweise auf die Benachrichtigungskanäle, die als Benachrichtigungspfade verwendet werden können.

Ein Benachrichtigungskanal muss vorhanden sein, bevor er in einer Benachrichtigungsrichtlinie verwendet werden kann. Die Benachrichtigungskanal-Deskriptoren werden Ihnen zur Verfügung gestellt. Allerdings müssen Sie die Kanäle erstellen, bevor sie verwendet werden können.

Informationen zum Konfigurieren von Benachrichtigungskanälen mit der Google Cloud Console finden Sie unter Benachrichtigungskanäle erstellen und verwalten.

Die in diesem Dokument verwendeten Codebeispiele werden aus dem Beispiel der Benachrichtigungsrichtlinien-API extrahiert, das unter Beispiel: Sicherung und Wiederherstellung beschrieben wird.

Informationen zur API

Die Ressource NotificationChannel unterstützt Vorgänge, mit denen Sie Ihre Benachrichtigungskanäle verwalten können. Es unterstützt auch Vorgänge zum Verwalten des Felds verificationStatus eines Kanals:

  • Einen Bestätigungscode senden
  • Einen Code generieren, mit dem der Verifizierungsstatus eines verifizierten Kanals auf andere identische Kanäle in demselben oder einem neuen Projekt kopiert wird
  • Den Kanal anhand des von den beiden vorherigen Vorgängen erstellten Codes verifizieren

Weitere Informationen finden Sie in den Referenzdokumenten zu notificationChannels.

Hinweise

Bitten Sie Ihren Administrator, Ihnen die IAM-Rolle Bearbeiter von Monitoring-Benachrichtigungskanälen (roles/monitoring.notificationChannelEditor) für Ihr Projekt zu gewähren, um die erforderlichen Berechtigungen zum Ansehen und Konfigurieren von Benachrichtigungskanälen mithilfe der Cloud Monitoring API zu erhalten. Weitere Informationen zum Zuweisen von Rollen finden Sie unter Zugriff verwalten.

Möglicherweise können Sie die erforderlichen Berechtigungen auch über benutzerdefinierte Rollen oder andere vordefinierte Rollen erhalten.

Weitere Informationen zu Cloud Monitoring-Rollen finden Sie unter Zugriff mit Identity and Access Management steuern.

Arten von Benachrichtigungskanälen auflisten

Monitoring bietet eine Reihe von integrierten Benachrichtigungskanaltypen. Die einzelnen Typen werden in NotificationChannelDescriptor beschrieben. Diese Deskriptoren haben ein type-Feld. Der Wert dieses Felds fungiert beim Erstellen von Instanzen dieses Kanaltyps als Kennzeichnung dafür. Mit dem folgenden Befehl können Sie die verfügbaren Kanaltypen abrufen, die allgemein unter Benachrichtigungskanäle erstellen und verwalten beschrieben werden:

$ gcloud beta monitoring channel-descriptors list --format='value(type)'
campfire
email
google_chat
hipchat
pagerduty
pubsub
slack
sms
webhook_basicauth
webhook_tokenauth

Wenn Ihr bevorzugter Benachrichtigungskanal nicht unterstützt wird, sollten Sie eine Pipeline erstellen, die Ihre Benachrichtigungen an Pub/Sub sendet. Ein Python-Beispiel, das Cold verwendet, finden Sie unter Benutzerdefinierte Benachrichtigungen mit Cloud Monitoring und Cloud Run erstellen. Weitere Beispiele finden Sie im Git-Repository für Cloud-Benachrichtigungen-Benachrichtigungen.

Verwenden Sie die Methode notificationChannelDescriptors.list, um alle Kanaldeskriptoren in einem Google Cloud-Projekt abzurufen. Die abgerufenen Deskriptoren sind schreibgeschützt.

Wenn Sie nach einem bestimmten Deskriptor suchen und dessen Namen kennen, können Sie die Methode notificationChannelDescriptors.get verwenden, um nur diesen Kanaldeskriptor abzurufen. Der Name eines Kanaldeskriptors hat das Format projects/[PROJECT_ID]/notificationChannelDescriptors/[CHANNEL_TYPE]. [CHANNEL_TYPE] muss einem der oben aufgeführten Typen entsprechen, zum Beispiel:

projects/[PROJECT_ID]/notificationChannelDescriptors/email

gcloud

Verwenden Sie den Befehl gcloud beta monitoring channel-descriptors list, um alle Benachrichtigungskanal-Deskriptoren in einem Google Cloud-Projekt aufzulisten:

gcloud beta monitoring channel-descriptors list

Bei Erfolg liefert der list-Befehl eine Liste aller Kanalbeschreibungen im angegebenen Projekt. Der Kanaldeskriptor email wird in der Liste zum Beispiel so angezeigt:

    ---
    description: A channel that sends notifications via email.
    displayName: Email
    labels:
    - description: An address to send email.
      key: email_address
    name: projects/[PROJECT_ID]/notificationChannelDescriptors/email
    type: email
    ---

Alle Kanaldeskriptoren enthalten folgende Felder:

  • name: Der vollständig qualifizierte Ressourcenname des Kanaldeskriptors
  • type: Der Teil des Namens, der den Typ des Kanals angibt
  • displayName: Eine Beschreibung des Felds type zu Anzeigezwecken
  • description: Eine kurze Beschreibung des Kanals
  • labels: Eine Reihe von Feldern, die für einen Kanaltyp spezifisch sind. Jeder Kanaltyp hat seine eigenen Labels.

Wenn ein Kanal erstellt wird, erhält er außerdem ein enabled -Feld mit dem Wert true.

Wenn Sie hingegen einen einzelnen Kanaldeskriptor abrufen möchten, verwenden Sie stattdessen gcloud beta monitoring channel-descriptors describe und geben Sie den Namen des Kanaldeskriptors an. Sie müssen den vollständig qualifizierten Namen nicht angeben. Mit beiden Befehlen wird beispielsweise die obige Liste zurückgegeben:

gcloud beta monitoring channel-descriptors describe email

gcloud beta monitoring channel-descriptors describe projects/[PROJECT_ID]/notificationChannelDescriptors/email

Weitere Informationen finden Sie in den Referenzen gcloud beta monitoring channel-descriptors list und describe. Der Befehl describe entspricht der Methode notificationChannelDescriptors.get in der API.

Benachrichtigungskanal erstellen

Sie können mit der Google Cloud CLI Benachrichtigungskanäle für Ihre Google Cloud-Projekte aus JSON- oder YAML-Dateien erstellen und programmatisch erstellen.

Sie müssen in seinem Deskriptor Werte für die Felder angeben, um einen Benachrichtigungskanal zu erstellen. Die meisten davon, wie type, sind in allen Deskriptoren von Benachrichtigungskanälen üblich. Siehe notificationChannelDescriptors.

Jeder Deskriptor verfügt auch über eine Reihe von Labels, die sich je nach Deskriptor unterscheiden. Wenn Sie die Labels für einen bestimmten Deskriptor sehen möchten, rufen Sie den Deskriptor mit dem Befehl gcloud beta monitoring channel-descriptors describe ab, der unter Arten von Benachrichtigungskanälen auflisten beschrieben wird. Wenn Sie beispielsweise den Kanaldeskriptor email abrufen, wird ein einzelnes Label angezeigt:

    labels:
    - description: An address to send email.
      key: email_address

Der Kanaldeskriptor pubsub enthält auch ein einzelnes Label, das das Pub/Sub-Thema identifiziert. Kanäle können jedoch mehrere Labels enthalten. Der Kanaldeskriptor slack hat beispielsweise zwei Labels:

    labels:
    - description: A permanent authentication token provided by Slack. This field is obfuscated by returning only a few characters of the key when fetched.
      key: auth_token
    - description: The Slack channel to which to post notifications.
      key: channel_name

Beim Abrufen des Kanaldeskriptors webhook_basicauth werden mehrere Labels angezeigt:

    labels:
    - description: The password. The field is obfuscated when the channel is fetched.
      key: password
    - description: The public URL to which to publish the webhook.
      key: url
    - description: The username.
      key: username

Unabhängig davon, ob Sie einen neuen Kanal programmatisch oder über die Befehlszeile erstellen, muss der Wert von type in Ihrer Spezifikation mit dem Feld type im entsprechenden Deskriptor des Benachrichtigungskanals übereinstimmen. Erforderliche Labelschlüssel müssen auch mit denen im Kanaldeskriptor übereinstimmen.

Einige Labels entsprechen Anmeldedaten, die zur Authentifizierung beim Dienstanbieter verwendet werden. Wenn Sie einen Kanal erstellen, müssen Sie die Werte für diese Labels vom Dienstanbieter beziehen. Der Erhalt von Anmeldedaten kann über eine Seite zum Generieren von API-Schlüsseln auf der Website des Anbieters oder den Abschluss eines OAuth-Anmeldevorgangs beim Anbieter erfolgen. Wie Sie solche Anmeldedaten abrufen können, hängt vom jeweiligen Dienstanbieter ab.

Das folgende Beispiel zeigt die Spezifikation eines neuen pubsub-Benachrichtigungskanals in JSON:

    {
      "type": "pubsub",
      "displayName": "Alert notifications",
      "description": "Pub/Sub channel for alert notifications",
      "labels": {
        "topic": "projects/[PROJECT_ID]/topics/notificationTopic"
      },
    }

Der type-Wert (pubsub) und der einzelne Labelschlüssel (topic) entsprechen den Feldern type und labels.key des betreffenden Kanaldeskriptors.

Kanäle sind standardmäßig aktiviert. Wenn Sie einen inaktiven Kanal erstellen möchten, können Sie das Feld enabled mit dem Wert false einschließen.

Die folgenden Beispiele veranschaulichen das Erstellen von Benachrichtigungskanälen.

gcloud

Verwenden Sie den Befehl gcloud beta monitoring channels create, um einen Benachrichtigungskanal in einem Google Cloud-Projekt zu erstellen. Zum Laden des Kanals aus einer Datei verwenden Sie das Flag --channel-content-from-file, um die Datei anzugeben.

Im folgenden Beispiel wird ein neuer Pub/Sub-Kanal aus der pubsub-channel.json-Datei erstellt:

gcloud beta monitoring channels create --channel-content-from-file="pubsub-channel.json"

Bei Erfolg gibt dieser Befehl den Namen des neuen Kanals zurück, zum Beispiel:

    Created notification channel [projects/[PROJECT_ID]/notificationChannels/1355376463305411567].

Weitere Informationen finden Sie in der Referenz gcloud beta monitoring channels create.

C#

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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)
    {
        try
        {
            bool updated = false;
            Console.WriteLine("Updating channel.\n{0}",
                channel.DisplayName);
            // This field is immutable and it is illegal to specify a
            // non-default value (UNVERIFIED or VERIFIED) in the
            // Create() or Update() operations.
            channel.VerificationStatus = NotificationChannel.Types
                .VerificationStatus.Unspecified;
            if (isSameProject)
                try
                {
                    channelClient.UpdateNotificationChannel(
                        null, channel);
                    updated = true;
                }
                catch (Grpc.Core.RpcException e)
                when (e.Status.StatusCode == StatusCode.NotFound)
                { }
            if (!updated)
            {
                // The channel no longer exists.  Recreate it.
                string oldName = channel.Name;
                channel.Name = null;
                var response = channelClient.CreateNotificationChannel(
                    projectName, channel);
                channelNameMap.Add(oldName, response.Name);
            }
        }
        catch (Exception e)
        {
            // If one failed, continue trying to update the others.
            exceptions.Add(e);
        }
    }
    foreach (AlertPolicy policy in backup.Policies)
    {
    }
    if (exceptions.Count > 0)
    {
        throw new AggregateException(exceptions);
    }
}

Node.js

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

// Creates clients
const alertClient = new monitoring.AlertPolicyServiceClient();
const notificationClient = new monitoring.NotificationChannelServiceClient();

async function replaceChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const alertPolicyId = '123456789012314';
  // const channelIds = [
  //   'channel-1',
  //   'channel-2',
  //   'channel-3',
  // ];

  const notificationChannels = channelIds.map(id =>
    notificationClient.projectNotificationChannelPath(projectId, id)
  );

  for (const channel of notificationChannels) {
    const updateChannelRequest = {
      updateMask: {
        paths: ['enabled'],
      },
      notificationChannel: {
        name: channel,
        enabled: {
          value: true,
        },
      },
    };
    try {
      await notificationClient.updateNotificationChannel(
        updateChannelRequest
      );
    } catch (err) {
      const createChannelRequest = {
        notificationChannel: {
          name: channel,
          notificationChannel: {
            type: 'email',
          },
        },
      };
      const newChannel =
        await notificationClient.createNotificationChannel(
          createChannelRequest
        );
      notificationChannels.push(newChannel);
    }
  }

  const updateAlertPolicyRequest = {
    updateMask: {
      paths: ['notification_channels'],
    },
    alertPolicy: {
      name: alertClient.projectAlertPolicyPath(projectId, alertPolicyId),
      notificationChannels: notificationChannels,
    },
  };
  const [alertPolicy] = await alertClient.updateAlertPolicy(
    updateAlertPolicyRequest
  );
  console.log(`Updated ${alertPolicy.name}.`);
}
replaceChannels();

Go

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

private static Map<String, String> restoreNotificationChannels(
    String projectId, List<NotificationChannel> channels, boolean isSameProject)
    throws IOException {
  Map<String, String> newChannelNames = Maps.newHashMap();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    for (NotificationChannel channel : channels) {
      // Update channel name if project ID is different.
      boolean channelUpdated = false;
      if (isSameProject) {
        try {
          NotificationChannel updatedChannel =
              client.updateNotificationChannel(NOTIFICATION_CHANNEL_UPDATE_MASK, channel);
          newChannelNames.put(channel.getName(), updatedChannel.getName());
          channelUpdated = true;
        } catch (Exception e) {
          channelUpdated = false;
        }
      }
      if (!channelUpdated) {
        NotificationChannel newChannel =
            client.createNotificationChannel(
                ProjectName.of(projectId),
                channel.toBuilder().clearName().clearVerificationStatus().build());
        newChannelNames.put(channel.getName(), newChannel.getName());
      }
    }
  }
  return newChannelNames;
}

PHP

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\CreateNotificationChannelRequest;
use Google\Cloud\Monitoring\V3\NotificationChannel;

/**
 * @param string $projectId Your project ID
 */
function alert_create_channel(string $projectId): void
{
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;

    $channel = new NotificationChannel();
    $channel->setDisplayName('Test Notification Channel');
    $channel->setType('email');
    $channel->setLabels(['email_address' => 'fake@example.com']);
    $createNotificationChannelRequest = (new CreateNotificationChannelRequest())
        ->setName($projectName)
        ->setNotificationChannel($channel);

    $channel = $channelClient->createNotificationChannel($createNotificationChannelRequest);
    printf('Created notification channel %s' . PHP_EOL, $channel->getName());
}

Python

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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)

Benachrichtigungskanäle in einem Projekt auflisten

Verwenden Sie die Methode notificationChannels.list, um alle Benachrichtigungskanäle in einem Google Cloud-Projekt abzurufen. Diese Methode unterstützt auch die Optionen filter und orderBy zum Eingrenzen und Sortieren der Ergebnisse. Weitere Informationen finden Sie unter Sortieren und Filtern.

Wenn Sie einen bestimmten Kanal suchen und dessen Namen kennen, können Sie mit der Methode notificationChannels.get gezielt diesen Kanal abrufen. Der Name eines Kanals hat das Format projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID], z. B.:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

Wenn Sie einen Kanal abrufen, werden aus Sicherheitsgründen unter Umständen vertrauliche Werte wie Authentifizierungstoken und API-Schlüssel verschleiert. Wenn Sie einen neuen Kanal durch Kopieren eines vorhandenen erstellen, müssen alle verschleierten Werte korrigiert werden.

gcloud

Verwenden Sie den Befehl gcloud beta monitoring channels list, um alle Benachrichtigungskanäle in einem Google Cloud-Projekt aufzulisten:

gcloud beta monitoring channels list

Bei Erfolg liefert der list-Befehl eine Liste aller Kanäle im angegebenen Projekt. Der obige Befehl könnte beispielsweise eine Liste mit den folgenden Einträgen zurückgeben:

    ---
    description: E-mail channel created by gcloud as a test
    displayName: test e-mail channel
    enabled: false
    labels:
      email_address: user@example.com
    name: projects/[PROJECT_ID]/notificationChannels/1355376463305411567
    type: email
    ---
    description: Pub/Sub channel for alert notifications
    displayName: Alert notifications
    enabled: true
    labels:
      topic: projects/[PROJECT_ID]/topics/notificationTopic
    name: projects/[PROJECT_ID]/notificationChannels/1355376463305411567
    type: pubsub

Wenn Sie hingegen einen einzelnen Kanal abrufen möchten, verwenden Sie stattdessen gcloud beta monitoring channels describe und geben Sie den Namen des Kanals an. Dieser Befehl gibt beispielsweise den oben angezeigten Pub/Sub-Kanal zurück:

gcloud beta monitoring channels describe projects/[PROJECT_ID]/notificationChannels/1355376463305411567


Weitere Informationen finden Sie in den Referenzen gcloud beta monitoring channels list und describe. Der Befehl describe entspricht der Methode notificationChannels.get in der API.

C#

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

static void ListNotificationChannels(string projectId)
{
    var client = NotificationChannelServiceClient.Create();
    var response = client.ListNotificationChannels(new ProjectName(projectId));
    foreach (NotificationChannel channel in response)
    {
        Console.WriteLine(channel.Name);
        if (channel.DisplayName != null)
        {
            Console.WriteLine(channel.DisplayName);
        }
        Console.WriteLine();
    }
}

Node.js

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

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

async function deleteChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const filter = 'A filter for selecting policies, e.g. description:"cloud"';

  const request = {
    name: client.projectPath(projectId),
    filter,
  };
  const channels = await client.listNotificationChannels(request);
  console.log(channels);
  for (const channel of channels[0]) {
    console.log(`Deleting channel ${channel.displayName}`);
    try {
      await client.deleteNotificationChannel({
        name: channel.name,
      });
    } catch (err) {
      // ignore error
    }
  }
}
deleteChannels();

Go

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

channelClient, err := monitoring.NewNotificationChannelClient(ctx)
if err != nil {
	return err
}
defer channelClient.Close()
channelReq := &monitoringpb.ListNotificationChannelsRequest{
	Name: "projects/" + projectID,
	// Filter:  "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
	// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
}
channelIt := channelClient.ListNotificationChannels(ctx, channelReq)
for {
	resp, err := channelIt.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	b.Channels = append(b.Channels, &channel{resp})
}

Java

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

private static List<NotificationChannel> getNotificationChannels(String projectId)
    throws IOException {
  List<NotificationChannel> notificationChannels = Lists.newArrayList();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    ListNotificationChannelsPagedResponse listNotificationChannelsResponse =
        client.listNotificationChannels(ProjectName.of(projectId));
    for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) {
      notificationChannels.add(channel);
    }
  }
  return notificationChannels;
}

PHP

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\ListNotificationChannelsRequest;

/**
 * @param string $projectId Your project ID
 */
function alert_list_channels($projectId)
{
    $projectName = 'projects/' . $projectId;
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $listNotificationChannelsRequest = (new ListNotificationChannelsRequest())
        ->setName($projectName);

    $channels = $channelClient->listNotificationChannels($listNotificationChannelsRequest);
    foreach ($channels->iterateAllElements() as $channel) {
        printf('Name: %s (%s)' . PHP_EOL, $channel->getDisplayName(), $channel->getName());
    }
}

Python

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

def list_notification_channels(project_name):
    """List alert notification channels in a project.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
    """

    client = monitoring_v3.NotificationChannelServiceClient()
    channels = client.list_notification_channels(name=project_name)
    print(
        tabulate.tabulate(
            [(channel.name, channel.display_name) for channel in channels],
            ("name", "display_name"),
        )
    )

Benachrichtigungskanal aus einem Projekt löschen

Verwenden Sie zum Löschen eines Benachrichtigungskanals aus einem Google Cloud-Projekt die Methode notificationChannels.delete und geben Sie den Namen des zu löschenden Benachrichtigungskanals an. Er entspricht dem Wert des Felds name und nicht dem displayName in der Instanz NotificationChannel. Der Name eines Kanals hat das Format projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID], z. B.:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

Wenn versucht wird, einen Kanal zu löschen, auf den von einer Benachrichtigungsrichtlinie verwiesen wird, wird er standardmäßig nicht gelöscht. Wenn Sie das Entfernen von Verweisen aus Benachrichtigungsrichtlinien erzwingen und den Kanal löschen möchten, setzen Sie die Option force auf true. Dadurch wird der Kanal automatisch aus allen Verweisrichtlinien entfernt.

gcloud

Verwenden Sie zum Löschen eines Benachrichtigungskanals gcloud beta monitoring channels delete und geben Sie den Namen des zu löschenden Kanals an. Mit dem folgenden Befehl wird beispielsweise der in einem anderen Beispiel erstellte Kanal email gelöscht:

gcloud beta monitoring channels delete projects/[PROJECT_ID]/notificationChannels/1355376463305411567

Weitere Informationen finden Sie in der Referenz gcloud beta monitoring channels delete.

C#

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Monitoring.V3;
using System;

partial class AlertSnippets
{
    public void DeleteNotificationChannel(
        string channelName = "projects/your-project-id/notificationChannels/123")
    {
        var client = NotificationChannelServiceClient.Create();
        client.DeleteNotificationChannel(
            name: NotificationChannelName.Parse(channelName),
            force: true);
        Console.WriteLine("Deleted {0}.", channelName);
    }
}

Go

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
)

// deleteChannel deletes the given channel. channelName should be of the form
// "projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]".
func deleteChannel(w io.Writer, channelName string) error {
	ctx := context.Background()

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

	req := &monitoringpb.DeleteNotificationChannelRequest{
		Name: channelName,
	}

	if err := client.DeleteNotificationChannel(ctx, req); err != nil {
		return fmt.Errorf("DeleteNotificationChannel: %w", err)
	}

	fmt.Fprintf(w, "Deleted channel %q", channelName)
	return nil
}

Java

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

static void deleteNotificationChannel(String channelName) throws IOException {
  String projectId = System.getProperty("projectId");
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    NotificationChannelName name = NotificationChannelName.of(projectId, channelName);
    client.deleteNotificationChannel(channelName, false);
    System.out.println("Deleted notification channel " + channelName);
  }
}

PHP

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\DeleteNotificationChannelRequest;

/**
 * @param string $projectId Your project ID
 * @param string $channelId
 */
function alert_delete_channel(string $projectId, string $channelId): void
{
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $channelName = $channelClient->notificationChannelName($projectId, $channelId);
    $deleteNotificationChannelRequest = (new DeleteNotificationChannelRequest())
        ->setName($channelName);

    $channelClient->deleteNotificationChannel($deleteNotificationChannelRequest);
    printf('Deleted notification channel %s' . PHP_EOL, $channelName);
}

Node.js

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

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

async function deleteChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const filter = 'A filter for selecting policies, e.g. description:"cloud"';

  const request = {
    name: client.projectPath(projectId),
    filter,
  };
  const channels = await client.listNotificationChannels(request);
  console.log(channels);
  for (const channel of channels[0]) {
    console.log(`Deleting channel ${channel.displayName}`);
    try {
      await client.deleteNotificationChannel({
        name: channel.name,
      });
    } catch (err) {
      // ignore error
    }
  }
}
deleteChannels();

Python

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

def delete_notification_channels(project_name, channel_ids, force=None):
    """Delete alert notification channels.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
        channel_ids list(str): List of IDs of notification channels to delete.
        force (bool): If true, the notification channels are deleted regardless
            of its in use by alert policies. If false, channels that are still
            referenced by an existing alerting policy will fail to be deleted.
    """

    channel_client = monitoring_v3.NotificationChannelServiceClient()
    for channel_id in channel_ids:
        channel_name = "{}/notificationChannels/{}".format(project_name, channel_id)
        try:
            channel_client.delete_notification_channel(name=channel_name, force=force)
            print("Channel {} deleted".format(channel_name))
        except ValueError:
            print("The parameters are invalid")
        except Exception as e:
            print("API call failed: {}".format(e))

Benachrichtigungskanal ändern

Verwenden Sie zum Ändern eines Benachrichtigungskanals die Methode notificationChannels.patch (in der REST API). In anderen API-Implementierungen und der Google Cloud CLI wird dies als update statt patch bezeichnet.

Ein Updatevorgang kann den vorhandenen Kanal vollständig ersetzen oder eine Teilmenge von Feldern ändern. Zum Beispiel können Sie den Kanal aktivieren und deaktivieren. Das Deaktivieren eines Kanals verhindert die Zustellung von Benachrichtigungen an den Kanal. Das Deaktivieren eines Kanals ist in der Regel unkomplizierter als das Entfernen des Kanals aus den Benachrichtigungsrichtlinien, die auf den Kanal verweisen, wenn die Änderung vorübergehend sein soll.

gcloud

Wenn Sie einen deaktivierten Benachrichtigungskanal aktivieren möchten, verwenden Sie den Befehl gcloud beta monitoring channels update und geben Sie das Flag --enabled an. Mit dem folgenden Befehl wird der Benachrichtigungskanal email, der in einem vorstehenden Beispiel im deaktivierten Status erstellt wurde, aktiviert:

gcloud beta monitoring channels update projects/[PROJECT_ID]/notificationChannels/1355376463305411567 --enabled

Wenn Sie eine Richtlinie deaktivieren möchten, verwenden Sie denselben Befehl und geben Sie das Flag --no-enabled an. Weitere Informationen finden Sie in der Referenz zu gcloud beta monitoring channels update. Der Befehl update entspricht der Methode notificationChannels.patch in der REST API.

C#

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using System;

partial class AlertSnippets
{
    public NotificationChannel EnableNotificationChannel(
        string channelName = "projects/your-project-id/notificationChannels/123")
    {
        var client = NotificationChannelServiceClient.Create();
        NotificationChannel channel = new NotificationChannel();
        channel.Enabled = true;
        channel.Name = channelName;
        var fieldMask = new FieldMask { Paths = { "enabled" } };
        channel = client.UpdateNotificationChannel(
            updateMask: fieldMask,
            notificationChannel: channel);
        Console.WriteLine("Enabled {0}.", channel.Name);
        return channel;
    }
}

Go

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"github.com/golang/protobuf/ptypes/wrappers"
	"google.golang.org/genproto/protobuf/field_mask"
)

// enableChannel enables the given channel. channelName should be of the form
// "projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]".
func enableChannel(w io.Writer, channelName string) error {
	ctx := context.Background()

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

	req := &monitoringpb.UpdateNotificationChannelRequest{
		UpdateMask: &field_mask.FieldMask{Paths: []string{"enabled"}},
		NotificationChannel: &monitoringpb.NotificationChannel{
			Name:    channelName,
			Enabled: &wrappers.BoolValue{Value: true},
		},
	}

	if _, err := client.UpdateNotificationChannel(ctx, req); err != nil {
		return fmt.Errorf("EnableNotificationChannel: %w", err)
	}

	fmt.Fprintf(w, "Enabled channel %q", channelName)
	return nil
}

Node.js

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

// Creates clients
const alertClient = new monitoring.AlertPolicyServiceClient();
const notificationClient = new monitoring.NotificationChannelServiceClient();

async function replaceChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const alertPolicyId = '123456789012314';
  // const channelIds = [
  //   'channel-1',
  //   'channel-2',
  //   'channel-3',
  // ];

  const notificationChannels = channelIds.map(id =>
    notificationClient.projectNotificationChannelPath(projectId, id)
  );

  for (const channel of notificationChannels) {
    const updateChannelRequest = {
      updateMask: {
        paths: ['enabled'],
      },
      notificationChannel: {
        name: channel,
        enabled: {
          value: true,
        },
      },
    };
    try {
      await notificationClient.updateNotificationChannel(
        updateChannelRequest
      );
    } catch (err) {
      const createChannelRequest = {
        notificationChannel: {
          name: channel,
          notificationChannel: {
            type: 'email',
          },
        },
      };
      const newChannel =
        await notificationClient.createNotificationChannel(
          createChannelRequest
        );
      notificationChannels.push(newChannel);
    }
  }

  const updateAlertPolicyRequest = {
    updateMask: {
      paths: ['notification_channels'],
    },
    alertPolicy: {
      name: alertClient.projectAlertPolicyPath(projectId, alertPolicyId),
      notificationChannels: notificationChannels,
    },
  };
  const [alertPolicy] = await alertClient.updateAlertPolicy(
    updateAlertPolicyRequest
  );
  console.log(`Updated ${alertPolicy.name}.`);
}
replaceChannels();

Java

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

private static Map<String, String> restoreNotificationChannels(
    String projectId, List<NotificationChannel> channels, boolean isSameProject)
    throws IOException {
  Map<String, String> newChannelNames = Maps.newHashMap();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    for (NotificationChannel channel : channels) {
      // Update channel name if project ID is different.
      boolean channelUpdated = false;
      if (isSameProject) {
        try {
          NotificationChannel updatedChannel =
              client.updateNotificationChannel(NOTIFICATION_CHANNEL_UPDATE_MASK, channel);
          newChannelNames.put(channel.getName(), updatedChannel.getName());
          channelUpdated = true;
        } catch (Exception e) {
          channelUpdated = false;
        }
      }
      if (!channelUpdated) {
        NotificationChannel newChannel =
            client.createNotificationChannel(
                ProjectName.of(projectId),
                channel.toBuilder().clearName().clearVerificationStatus().build());
        newChannelNames.put(channel.getName(), newChannel.getName());
      }
    }
  }
  return newChannelNames;
}

PHP

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\ApiCore\ApiException;
use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\CreateAlertPolicyRequest;
use Google\Cloud\Monitoring\V3\CreateNotificationChannelRequest;
use Google\Cloud\Monitoring\V3\NotificationChannel;
use Google\Cloud\Monitoring\V3\NotificationChannel\VerificationStatus;
use Google\Cloud\Monitoring\V3\UpdateAlertPolicyRequest;
use Google\Cloud\Monitoring\V3\UpdateNotificationChannelRequest;

/**
 * @param string $projectId Your project ID
 */
function alert_restore_policies(string $projectId): void
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);

    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);

    print('Loading alert policies and notification channels from backup.json.' . PHP_EOL);
    $projectName = 'projects/' . $projectId;
    $record = json_decode((string) file_get_contents('backup.json'), true);
    $isSameProject = $projectName == $record['project_name'];

    # Convert dicts to AlertPolicies.
    $policies = [];
    foreach ($record['policies'] as $policyArray) {
        $policy = new AlertPolicy();
        $policy->mergeFromJsonString((string) json_encode($policyArray));
        $policies[] = $policy;
    }

    # Convert dicts to NotificationChannels
    $channels = [];
    foreach (array_filter($record['channels']) as $channelArray) {
        $channel = new NotificationChannel();
        $channel->mergeFromJsonString((string) json_encode($channelArray));
        $channels[] = $channel;
    }

    # Restore the channels.
    $channelNameMap = [];
    foreach ($channels as $channel) {
        $updated = false;
        printf('Updating channel %s' . PHP_EOL, $channel->getDisplayName());

        # This field is immutable and it is illegal to specify a
        # non-default value (UNVERIFIED or VERIFIED) in the
        # Create() or Update() operations.
        $channel->setVerificationStatus(
            VerificationStatus::VERIFICATION_STATUS_UNSPECIFIED
        );

        if ($isSameProject) {
            try {
                $updateNotificationChannelRequest = (new UpdateNotificationChannelRequest())
                    ->setNotificationChannel($channel);
                $channelClient->updateNotificationChannel($updateNotificationChannelRequest);
                $updated = true;
            } catch (ApiException $e) {
                # The channel was deleted.  Create it below.
                if ($e->getStatus() !== 'NOT_FOUND') {
                    throw $e;
                }
            }
        }

        if (!$updated) {
            # The channel no longer exists.  Recreate it.
            $oldName = $channel->getName();
            $channel->setName('');
            $createNotificationChannelRequest = (new CreateNotificationChannelRequest())
                ->setName($projectName)
                ->setNotificationChannel($channel);
            $newChannel = $channelClient->createNotificationChannel($createNotificationChannelRequest);
            $channelNameMap[$oldName] = $newChannel->getName();
        }
    }

    # Restore the alerts
    foreach ($policies as $policy) {
        printf('Updating policy %s' . PHP_EOL, $policy->getDisplayName());
        # These two fields cannot be set directly, so clear them.
        $policy->clearCreationRecord();
        $policy->clearMutationRecord();

        $notificationChannels = $policy->getNotificationChannels();

        # Update old channel names with new channel names.
        foreach ($notificationChannels as $i => $channel) {
            if (isset($channelNameMap[$channel])) {
                $notificationChannels[$i] = $channelNameMap[$channel];
            }
        }

        $updated = false;
        if ($isSameProject) {
            try {
                $updateAlertPolicyRequest = (new UpdateAlertPolicyRequest())
                    ->setAlertPolicy($policy);
                $alertClient->updateAlertPolicy($updateAlertPolicyRequest);
                $updated = true;
            } catch (ApiException $e) {
                # The policy was deleted.  Create it below.
                if ($e->getStatus() !== 'NOT_FOUND') {
                    throw $e;
                }
            }
        }

        if (!$updated) {
            # The policy no longer exists.  Recreate it.
            $oldName = $policy->getName();
            $policy->setName('');
            foreach ($policy->getConditions() as $condition) {
                $condition->setName('');
            }
            $createAlertPolicyRequest = (new CreateAlertPolicyRequest())
                ->setName($projectName)
                ->setAlertPolicy($policy);
            $policy = $alertClient->createAlertPolicy($createAlertPolicyRequest);
        }
        printf('Updated %s' . PHP_EOL, $policy->getName());
    }
    print('Restored alert policies and notification channels from backup.json.');
}

Python

Richten Sie zur Authentifizierung bei Monitoring Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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)

Protokolle des Benachrichtigungskanals ansehen

Im Log-Explorer können Sie Fehler des Benachrichtigungskanals ansehen:

  1. Wählen Sie im Navigationsbereich der Google Cloud Console Logging und anschließend Log-Explorer aus:

    Zum Log-Explorer

  2. Geben Sie Ihre Abfrage ein und führen Sie sie aus. Informationen zu Abfragen speziell für Benachrichtigungskanalfehler finden Sie unter Cloud Monitoring-Abfragen.