Crea y administra canales de notificaciones con la API

La API de Cloud Monitoring y Google Cloud CLI te permiten crear y administrar de forma programática los canales de notificación que Cloud Monitoring usa para alertarte a ti o a tu equipo de guardia cuando se activa una política de alertas. Con las bibliotecas cliente o Google Cloud CLI, creas canales de notificaciones a partir de descriptores de canales de notificaciones integrados y, luego, haces referencia a esos canales en tus políticas de alertas.

Para configurar canales de notificaciones en la consola de Google Cloud , consulta Cómo crear y administrar canales de notificaciones. Los ejemplos de código de este documento provienen del ejemplo de la API de alerting-policy en Ejemplo: copia de seguridad y restablecimiento.

Acerca de la API

El recurso NotificationChannel admite operaciones que te permiten administrar tus canales de notificaciones. También admite operaciones relacionadas con la administración del campo verificationStatus de un canal:

  • Enviar un código de verificación
  • Generar un código para copiar el estado de verificación de un canal verificado en otros canales idénticos en el mismo proyecto o en uno nuevo
  • Verificar el canal mediante el código creado en las dos operaciones anteriores

Para obtener más información, consulta los documentos de referencia de notificationChannels.

Limitaciones

  • Tipos de canales obsoletos: Los tipos de canales campfire y hipchat quedaron obsoletos. No crees canales nuevos de estos tipos.
  • Políticas de almacenamiento de mensajes de Pub/Sub: Si configuras una política de almacenamiento de mensajes o restricciones de residencia de datos para un tema de Pub/Sub, es posible que Monitoring no pueda publicar en el tema. Para obtener más información, consulta el error FAILED_PRECONDITION.
  • Llamadas a la API simultáneas: Diseña tu aplicación para que llame a la API de Cloud Monitoring desde un solo subproceso cuando crees, modifiques o borres un canal de notificación en un proyecto de Google Cloud .

Antes de comenzar

  • Para obtener los permisos que necesitas para ver y configurar canales de notificaciones con la API de Cloud Monitoring, pídele a tu administrador que te otorgue el rol de IAM de editor de Monitoring NotificationChannel (roles/monitoring.notificationChannelEditor) en tu proyecto. Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.

    También puedes obtener los permisos necesarios a través de roles personalizados o cualquier otro rol predefinido.

    Para obtener más información sobre los roles de Cloud Monitoring, consulta Controla el acceso con Identity and Access Management.

  • Selecciona la pestaña que corresponda a la forma en que planeas usar las muestras de esta página:

    gcloud

    En la consola de Google Cloud , activa Cloud Shell.

    Activa Cloud Shell

    En la parte inferior de la consola de Google Cloud , se inicia una sesión de Cloud Shell en la que se muestra una ventana de línea de comandos. Cloud Shell es un entorno de shell con Google Cloud CLI ya instalada y con valores ya establecidos para el proyecto actual. La sesión puede tardar unos segundos en inicializarse.

    C#

    Para usar las muestras de .NET de esta página en un entorno de desarrollo local, instala e inicializa la gcloud CLI y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.

    2. Si usas un proveedor de identidad (IdP) externo, primero debes acceder a gcloud CLI con tu identidad federada.

    3. Si usas una shell local, crea credenciales de autenticación locales para tu cuenta de usuario:

      gcloud auth application-default login

      No es necesario que lo hagas si usas Cloud Shell.

      Si se muestra un error de autenticación y usas un proveedor de identidad (IdP) externo, confirma que accediste a la gcloud CLI con tu identidad federada.

    Para obtener más información, consulta Configura ADC para un entorno de desarrollo local en la documentación de autenticación de Google Cloud .

    Go

    Para usar las muestras de Go de esta página en un entorno de desarrollo local, instala e inicializa la gcloud CLI y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.

    2. Si usas un proveedor de identidad (IdP) externo, primero debes acceder a gcloud CLI con tu identidad federada.

    3. Si usas una shell local, crea credenciales de autenticación locales para tu cuenta de usuario:

      gcloud auth application-default login

      No es necesario que lo hagas si usas Cloud Shell.

      Si se muestra un error de autenticación y usas un proveedor de identidad (IdP) externo, confirma que accediste a la gcloud CLI con tu identidad federada.

    Para obtener más información, consulta Configura ADC para un entorno de desarrollo local en la documentación de autenticación de Google Cloud .

    Java

    Para usar las muestras de Java de esta página en un entorno de desarrollo local, instala e inicializa la gcloud CLI y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.

    2. Si usas un proveedor de identidad (IdP) externo, primero debes acceder a gcloud CLI con tu identidad federada.

    3. Si usas una shell local, crea credenciales de autenticación locales para tu cuenta de usuario:

      gcloud auth application-default login

      No es necesario que lo hagas si usas Cloud Shell.

      Si se muestra un error de autenticación y usas un proveedor de identidad (IdP) externo, confirma que accediste a la gcloud CLI con tu identidad federada.

    Para obtener más información, consulta Configura ADC para un entorno de desarrollo local en la documentación de autenticación de Google Cloud .

    Node.js

    Para usar las muestras de Node.js de esta página en un entorno de desarrollo local, instala e inicializa la gcloud CLI y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.

    2. Si usas un proveedor de identidad (IdP) externo, primero debes acceder a gcloud CLI con tu identidad federada.

    3. Si usas una shell local, crea credenciales de autenticación locales para tu cuenta de usuario:

      gcloud auth application-default login

      No es necesario que lo hagas si usas Cloud Shell.

      Si se muestra un error de autenticación y usas un proveedor de identidad (IdP) externo, confirma que accediste a la gcloud CLI con tu identidad federada.

    Para obtener más información, consulta Configura ADC para un entorno de desarrollo local en la documentación de autenticación de Google Cloud .

    PHP

    Para usar las muestras de PHP de esta página en un entorno de desarrollo local, instala e inicializa la gcloud CLI y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.

    2. Si usas un proveedor de identidad (IdP) externo, primero debes acceder a gcloud CLI con tu identidad federada.

    3. Si usas una shell local, crea credenciales de autenticación locales para tu cuenta de usuario:

      gcloud auth application-default login

      No es necesario que lo hagas si usas Cloud Shell.

      Si se muestra un error de autenticación y usas un proveedor de identidad (IdP) externo, confirma que accediste a la gcloud CLI con tu identidad federada.

    Para obtener más información, consulta Configura ADC para un entorno de desarrollo local en la documentación de autenticación de Google Cloud .

    Python

    Para usar las muestras de Python de esta página en un entorno de desarrollo local, instala e inicializa la gcloud CLI y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.

    2. Si usas un proveedor de identidad (IdP) externo, primero debes acceder a gcloud CLI con tu identidad federada.

    3. Si usas una shell local, crea credenciales de autenticación locales para tu cuenta de usuario:

      gcloud auth application-default login

      No es necesario que lo hagas si usas Cloud Shell.

      Si se muestra un error de autenticación y usas un proveedor de identidad (IdP) externo, confirma que accediste a la gcloud CLI con tu identidad federada.

    Para obtener más información, consulta Configura ADC para un entorno de desarrollo local en la documentación de autenticación de Google Cloud .

  • Si planeas usar Google Cloud CLI, configura el proyecto predeterminado:

    gcloud config set project PROJECT_ID
    

    Antes de ejecutar el comando anterior, reemplaza lo siguiente:

    • PROJECT_ID: Es el identificador del proyecto. Para las configuraciones de App Hub, selecciona el proyecto host o el proyecto de administración de App Hub.

Enumera los tipos de canales de notificaciones

Monitoring proporciona varios tipos de canales de notificaciones integrados. Cada uno de estos tipos se describe en un NotificationChannelDescriptor. Cada descriptor tiene un campo type cuyo valor identifica el tipo de canal cuando creas una instancia del canal. Para recuperar una lista de los tipos de canales que puedes crear con la API de Cloud Monitoring o Google Cloud CLI, ingresa el siguiente comando:

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

Si no se admite tu canal de notificaciones preferido, considera crear una canalización que dependa del envío de tus notificaciones a Pub/Sub. Para ver un ejemplo en Python que usa Flask, consulta Crea notificaciones personalizadas con Cloud Monitoring y Cloud Run. Para ver otros ejemplos, consulta el repositorio de Git cloud-alerting-notification-forwarding.

Enumera todos los tipos de canales

Para recuperar todos los descriptores de canales en un proyecto de Google Cloud , usa el comandogcloud beta monitoring channel-descriptors list o el método de la API denotificationChannelDescriptors.list. Los descriptores recuperados son de solo lectura.

gcloud beta monitoring channel-descriptors list

Si se ejecuta correctamente, el comando list proporciona una lista de todos los descriptores de canales del proyecto especificado. Por ejemplo, el descriptor de canal email aparece en la lista de la siguiente manera:

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

Todos los descriptores de canales incluyen estos campos:

  • name: Es el nombre del recurso completamente calificado del descriptor del canal.
  • type: Es la parte del nombre que indica el tipo de canal.
  • displayName: Es una descripción del campo type que se muestra.
  • description: Es una breve descripción del canal.
  • labels: Un conjunto de campos específicos para un tipo de canal. Cada tipo de canal tiene su propio conjunto de etiquetas.

Cuando se crea un canal, también obtiene un campo enabled, con el valor true de forma predeterminada.

Cómo enumerar un tipo de canal específico

Si buscas un descriptor específico y conoces su nombre, usa gcloud beta monitoring channel-descriptors describe o el método de la API de notificationChannelDescriptors.get. El nombre de un descriptor de canal tiene el formato projects/[PROJECT_ID]/notificationChannelDescriptors/[CHANNEL_TYPE]. [CHANNEL_TYPE] debe ser uno de los tipos enumerados anteriormente. Por ejemplo:

gcloud beta monitoring channel-descriptors describe email

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

Consulta las referencias gcloud beta monitoring channel-descriptors list y describe para obtener más información. El comando describe corresponde al método notificationChannelDescriptors.get en la API.

Crea un canal de notificaciones

Puedes crear canales de notificación para tus proyectos de Google Cloud desde archivos JSON o YAML con Google Cloud CLI, y también puedes crearlos de forma programática.

Para crear un canal de notificación, debes completar los valores de los campos de su descriptor. La mayoría, como type, son comunes en todos los descriptores de canales de notificaciones; consulta notificationChannelDescriptors.

Cada descriptor posee, además, un conjunto de etiquetas que varía de un descriptor a otro. Para ver el conjunto de etiquetas de un descriptor en particular, recupera el descriptor con el comando gcloud beta monitoring channel-descriptors describe que se describe en Cómo enumerar los tipos de canales de notificación. Por ejemplo, cuando se recupera el descriptor de canal email, se muestra una sola etiqueta:

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

El descriptor del canal pubsub también contiene una sola etiqueta, que identifica el tema de Pub/Sub. Sin embargo, los canales pueden contener varios sellos. Por ejemplo, el descriptor de canal slack tiene dos etiquetas:

    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

Cuando se recupera el descriptor de canal webhook_basicauth, se muestran varias etiquetas:

    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

Ya sea que crees un canal nuevo de manera programática o desde la línea de comandos, el valor de type en tu especificación debe coincidir con el campo type en el descriptor de canal de notificaciones correspondiente. Las claves de etiquetas necesarias también deben coincidir con las del descriptor de canal.

Algunas etiquetas corresponden a las credenciales que se usan para autenticarse con el proveedor. Cuando se crea un canal, los valores para estas etiquetas deben obtenerse del proveedor. Para obtener una credencial, es posible que debas usar una página de generación de claves de API en el sitio web del proveedor o completar un flujo de acceso con OAuth con el proveedor. Los detalles específicos para obtener esa credencial dependen de cada proveedor.

Los canales están habilitados de manera predeterminada. Si deseas crear un canal inactivo, puedes incluir el campo enabled con el valor false.

Los siguientes ejemplos ilustran la creación de los canales de notificación.

Ejemplo: Crea un canal de notificaciones de Pub/Sub con gcloud CLI

Para crear un canal de notificaciones en un proyecto Google Cloud , usa el comando gcloud beta monitoring channels create. Para cargar el canal desde un archivo, usa la marca --channel-content-from-file para especificar el archivo.

Por ejemplo, a continuación, se muestra la especificación de un nuevo canal de notificación pubsub en JSON:

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

El valor de type (pubsub) y la clave de etiqueta única (topic) coinciden con los campos type y labels.key del descriptor de canal correspondiente.

Con el siguiente ejemplo, se crea un nuevo canal de Pub/Sub desde el archivo pubsub-channel.json:

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

Si se ejecuta correctamente, este comando devuelve el nombre del canal nuevo. Por ejemplo:

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

Cuando crees un canal de notificación de pubsub, asegúrate de autorizar la cuenta de servicio de notificaciones para publicar en el tema. También ten en cuenta que, si el tema tiene una política de almacenamiento de mensajes o restricciones de residencia de datos, es posible que Monitoring no pueda publicar en él. Consulta el error FAILED_PRECONDITION.

Ejemplo: Crea un canal de notificaciones con bibliotecas cliente

En los siguientes ejemplos, se muestra cómo crear un canal de notificación con una biblioteca cliente:

C#

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

static void RestorePolicies(string projectId, string filePath)
{
    var policyClient = AlertPolicyServiceClient.Create();
    var channelClient = NotificationChannelServiceClient.Create();
    List exceptions = new List();
    var backup = JsonConvert.DeserializeObject(
        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>();
    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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

private static Map, String> restoreNotificationChannels(
    String projectId, List channels, boolean isSameProject)
    throws IOException {
  Map, 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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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/'.
        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)

Ejemplo: Crea un canal de notificaciones de Slack

Para configurar un canal de notificaciones para una app de Slack, haz lo siguiente:

  1. Configura tu app de Slack:

    1. Si aún no tienes una app de Slack, sigue la documentación de referencia de Slack para crear una y, luego, instálala en tu espacio de trabajo.
    2. Configura tu app de Slack con permisos de OAuth para chat:write y chat:write.public.
    3. Copia el token de OAuth del usuario bot de la app.
  2. Crea un archivo que defina la configuración de tu canal de notificaciones. Incluye una etiqueta en la que la clave auth_token tenga el valor del token de OAuth del usuario bot de tu app de Slack. Por ejemplo:

    {
      "description": "A Slack notification channel",
      "displayName": "Slack",
      "type": "slack",
      "enabled": true,
      "labels": {
        "auth_token": "OAUTH_TOKEN_VALUE",
        "channel_name": "SLACK_CHANNEL_NAME"
      }
    }
    
  3. Ejecuta el siguiente comando para crear el canal de notificación:

    gcloud beta monitoring channels create --channel-content-from-file="FILE_NAME"
    

Enumera los canales de notificaciones de un proyecto

Para recuperar todos los canales de notificaciones en un proyecto Google Cloud , usa el método notificationChannels.list. Este método también admite las opciones filter y orderBy para restringir y ordenar los resultados. Consulta Ordenamiento y filtrado.

Si buscas un canal específico y sabes su nombre, puedes usar el método notificationChannels.get para recuperar solo ese canal. El nombre de un canal tiene el formato projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]. Por ejemplo:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

Cuando recuperas un canal, los valores sensibles, como los tokens de autenticación y las claves de API, pueden ofuscarse por motivos de seguridad. Si copias un canal existente para crear uno nuevo, debes corregir los valores ofuscados.

gcloud

Para enumerar todos los canales de notificación en un proyecto de Google Cloud , usa el comandogcloud beta monitoring channels list:

gcloud beta monitoring channels list

Si se ejecuta de forma correcta, el comando list proporciona una lista de todos los canales del proyecto especificado. Por ejemplo, el comando anterior podría devolver una lista que incluya las siguientes entradas:

    ---
    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 notifications
    displayName: Notifications
    enabled: true
    labels:
      topic: projects/[PROJECT_ID]/topics/notificationTopic
    name: projects/[PROJECT_ID]/notificationChannels/1355376463305411567
    type: pubsub

Para enumerar un solo canal, usa gcloud beta monitoring channels describe y especifica el nombre del canal. Por ejemplo, este comando devuelve el canal de Pub/Sub que se muestra en la lista anterior:

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

Consulta las referencias gcloud beta monitoring channels list y describe para obtener más información. El comando describe corresponde al método notificationChannels.get en la API.

C#

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

private static List getNotificationChannels(String projectId)
    throws IOException {
  List 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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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/'.
    """

    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"),
        )
    )

Borra un canal de notificación de un proyecto

Para borrar un canal de notificaciones de un proyecto Google Cloud , usa el método notificationChannels.delete y proporciona el nombre del canal de notificaciones que se borrará. El nombre de un canal es el valor del campo name, no el displayName, en la instancia de NotificationChannel. El nombre de un canal tiene el formato projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]. Por ejemplo:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

De forma predeterminada, si intentas borrar un canal al que hace referencia una política de alertas, no se borrará el canal. Para forzar la eliminación de las referencias de las políticas de alertas y borrar el canal, establece la opción force en true. Esta opción quita automáticamente el canal de todas las políticas de referencia.

gcloud

Para borrar un canal de notificaciones, usa gcloud beta monitoring channels delete y especifica el nombre del canal que deseas borrar. Por ejemplo, con el siguiente comando, se borra el canal email, que se creó en otro ejemplo:

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

Consulta la referencia de gcloud beta monitoring channels delete para obtener más información.

C#

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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/'.
        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))

Cómo modificar un canal de notificaciones

Para modificar un canal de notificaciones, usa el método notificationChannels.patch (en la API de REST). Otras implementaciones de la API y Google Cloud CLI llaman a este update en lugar de patch.

Una operación de actualización puede reemplazar el canal existente por completo o puede modificar un subconjunto de campos. Por ejemplo, puedes habilitar o inhabilitar el canal. La inhabilitación de un canal impide la entrega de notificaciones al canal. Si se pretende que el cambio sea temporal, por lo general, es más conveniente inhabilitar un canal que eliminarlo de las políticas de alertas que hacen referencia a él.

gcloud

Para habilitar un canal de notificaciones inhabilitado, usa el comando gcloud beta monitoring channels update y proporciona la marca --enabled. Con el siguiente comando, se habilita el canal de notificaciones email que se creó, en el estado inhabilitado, en un ejemplo anterior:

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

Para inhabilitar un canal de notificaciones, usa el mismo comando y proporciona la marca --no-enabled. Consulta la referencia de gcloud beta monitoring channels update para obtener más información. El comando update corresponde al método notificationChannels.patch en la API de REST.

C#

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

private static Map, String> restoreNotificationChannels(
    String projectId, List channels, boolean isSameProject)
    throws IOException {
  Map, 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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para autenticarte en Monitoring, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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/'.
        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)

Cómo ver los registros del canal de notificaciones

Puedes usar el Explorador de registros para ver los errores del canal de notificaciones:

  1. En la consola de Google Cloud , ve a la página Explorador de registros del :

    Ir al Explorador de registros

    Si usas la barra de búsqueda para encontrar esta página, selecciona el resultado cuyo subtítulo es Logging.

  2. Ingresa y ejecuta tu consulta. Para consultas específicas sobre errores del canal de notificaciones, consulta Consultas de Cloud Monitoring.