Managing Notification Channels by API

Alerting policies typically have some way to let you know when they have been triggered. These “ways to let you know” are called notification channels. There are several available channel types; each is type is described in a notification-channel descriptor. A notification channel of a certain type is an instance of that type's descriptor. Your alerting policies include references to the notification channels to use as notification pathways.

A notification channel must exist before it can be used in an alerting policy. The notification-channel descriptors are provided to you, but you have to create the channels before they can be used.

The code samples used here are extracted from the alerting-policy API example, described in Example: backup and restore.

Channel descriptors

Stackdriver provides a number of built-in notification-channel types. Each of these types is described in a NotificationChannelDescriptor. These descriptors have a type field, and the value of this field acts as an identifier for it when creating instances of that channel type. The available channel types, described more generally in Notification options, are currently:

  • campfire
  • email
  • hipchat
  • pagerduty
  • slack
  • sms
  • webhook_basicauth
  • webhook_tokenauth

To retrieve all the channel descriptors in a project, use the notificationChannelDescriptors.list method. The retrieved descriptors are read-only.

If you are looking for a specific descriptor and you know its name, you can use the notificationChannelDescriptors.get method to retrieve only that channel descriptor. The name of a channel descriptor has the format projects/[PROJECT_ID]/notificationChannelDescriptors/[CHANNEL_TYPE] [CHANNEL_TYPE] must be one of the types listed above, for example:

projects/a-gcp-project/notificationChannelDescriptors/email

GCLOUD COMMAND

To list all the notification-channel descriptors in a project, use the gcloud alpha monitoring channel-descriptors list command:

gcloud alpha monitoring channel-descriptors list

If successful, the list command provides a listing of all the channel descriptors in the specified project. For example, the email channel descriptor appears in the list like this:

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

To list a single channel descriptor, use gcloud alpha monitoring channel-descriptors describe, instead, and specify the name of the channel descriptor. For example, this command returns only the listing above:

gcloud alpha monitoring channel-descriptors describe projects/a-gcp-project/notificationChannelDescriptors/email

See the gcloud alpha monitoring channel-descriptors list and describe references for more information. The describe command corresponds to the notificationChannelDescriptors.get method in the API.

Notification channels

A notification channel is an instance of one of the notification-channel descriptors discussed in Channel descriptors.

The NotificationChannel resource supports five operations:

  • Creating new channels
  • Deleting existing channels
  • Retrieving specific channels
  • Retrieving all channels
  • Modifying existing channels

There are three other operations related to managing the verificationStatus field of a channel:

  • Sending a verification code
  • Generating a code for copying the verification status of a verified channel to other identical channels in the same or a new project
  • Verifying the channel using the code created by the previous two operations

See the notificationChannels reference for more information on them.

Creating channels

You can create notification channels from JSON or YAML files using the gcloud command-line utility, and you can create them programmatically.

For example, here's a JSON representation of a new notification channel of the type email:

{
  "type": "email",
  "displayName": "test e-mail channel",
  "description": "E-mail channel created by gcloud as a test",
  "labels": {
    "email_address": "user@example.com"
  },
  "enabled": false
}

The value of the type field here must match the type field in one of the available notification-channel descriptors, as described in Channel descriptors.

The following examples illustrate the creation of notification channels.

GCLOUD COMMAND

To create a notification channel in a project, use the glcoud alpha monitoring channels create command. To load the channel from a file, use the --channel-content-from-file flag to specify the file.

The following example creates a new e-mail channel in a-gcp-project from the new-email-channel.json file:

gcloud alpha monitoring channels create --channel-content-from-file="new-email-channel.json"

If successful, this command returns the name of the new channel, for example:

Created notification channel [projects/a-gcp-project/notificationChannels/1355376463305411567].

See the gcloud alpha monitoring channels create reference for more information.

C#

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

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);
    }
}

Go

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

// 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
	}
	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}

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

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

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

Python

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

def restore(project_name):
    print('Loading alert policies and notification channels from backup.json.')
    record = json.load(open('backup.json', 'rt'))
    is_same_project = project_name == record['project_name']
    # Convert dicts to AlertPolicies.
    policies_json = [json.dumps(policy) for policy in record['policies']]
    policies = [google.protobuf.json_format.Parse(
        policy_json, monitoring_v3.types.alert_pb2.AlertPolicy())
        for policy_json in policies_json]
    # Convert dicts to NotificationChannels
    channels_json = [json.dumps(channel) for channel in record['channels']]
    channels = [google.protobuf.json_format.Parse(
        channel_json, monitoring_v3.types.notification_pb2.
        NotificationChannel()) 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.enums.NotificationChannel.\
            VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED

        if is_same_project:
            try:
                channel_client.update_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
            channel.ClearField("name")
            new_channel = channel_client.create_notification_channel(
                project_name, 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.
        policy.ClearField('creation_record')
        policy.ClearField('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(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
            policy.ClearField("name")
            for condition in policy.conditions:
                condition.ClearField("name")
            policy = alert_client.create_alert_policy(project_name, policy)
        print('Updated', policy.name)

Retrieving channels

To retrieve all the notification channels in a project, use the notificationChannels.list method. This method also supports filter and orderBy options to restrict and sort the results; see Sorting and Filtering.

If you are looking for a specific channel and you know its name, you can use the notificationChannels.get method to retrieve only that channel. The name of a channel has the format projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID], for example:

projects/a-gcp-project/notificationChannels/1355376463305411567

GCLOUD COMMAND

To list all the notification channels in a project, use the gcloud alpha monitoring channels list command:

gcloud alpha monitoring channels list

If successful, the list command provides a listing of all the channels in the specified project. For example, the command above results in a list that includes the following:

---
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/a-gcp-project/notificationChannels/1355376463305411567
type: email
---

To list a single channel, use gcloud alpha monitoring channels describe, instead, and specify the name of the channel. For example, this command returns only the listing above:

gcloud alpha monitoring channels describe projects/a-gcp-project/notificationChannels/1355376463305411567

See the gcloud alpha monitoring channels list and describe references for more information. The describe command corresponds to the notificationChannels.get method in the API.

C#

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

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();
    }
}

Go

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

channelClient, err := monitoring.NewNotificationChannelClient(ctx)
if err != nil {
	return err
}
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

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

private List<NotificationChannel> getNotificationChannels(String projectId) {
  List<NotificationChannel> notificationChannels = Lists.newArrayList();
  ListNotificationChannelsPagedResponse listNotificationChannelsResponse =
      notificationChannelClient.listNotificationChannels(ProjectName.of(projectId));
  for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) {
    notificationChannels.add(channel);
  }
  return notificationChannels;
}

Python

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

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

Deleting channels

To delete a notification channel from a project, use the notificationChannels.delete method, and supply the name of the notification channel to delete. The name of a channel is the value of the name field, not the displayName, in the NotificationChannel instance. The name of a channel has the format projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID], for example:

projects/a-gcp-project/notificationChannels/1355376463305411567

By default, if you attempt to delete a channel that is referenced by an alerting policy, the channel will not be deleted. To force the removal of references from alerting policies and delete the channel, set the force option to true.

GCLOUD COMMAND

To delete a notification channel, use gcloud alpha monitoring channels delete, and specify the name of the channel to delete. For example, the following command deletes the email channel created in another example:

gcloud alpha monitoring channels delete projects/a-gcp-project/notificationChannels/1355376463305411567

See the gcloud alpha monitoring channels delete reference for more information.

Modifying channels

To modify a notification channel, use the notificationChannels.patch method (in the REST API). Other API implementations and the gcloud interface call this update instead of patch.

An update operation can wholly replace the existing channel, or it can modify a subset of fields. For example, you can enable and disable the channel. Disabling a channel prevents delivery of notifications to the channel. Disabling a channel is typically more convenient than removing the channel from the alerting policies that refer to it, if the change is intended to be temporary.

GCLOUD COMMAND

To enable a notification channel that is disabled, use the gcloud alpha monitoring channels update command, and provide the --enabled flag. The following command enables the email notification channel created—in the disabled state—in a previous example:

gcloud alpha monitoring channels update projects/a-gcp-project/notificationChannels/1355376463305411567 --enabled

To disable a policy, use the same command and provide the --no-enabled flag. See the gcloud alpha monitoring channels update reference for more information. The update command corresponds to the notificationChannels.patch method in the REST API.

C#

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

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);
    }
}

Go

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

// 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
	}
	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}

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

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

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

Python

For more on installing and creating a Monitoring client, refer to Monitoring Client Libraries.

def restore(project_name):
    print('Loading alert policies and notification channels from backup.json.')
    record = json.load(open('backup.json', 'rt'))
    is_same_project = project_name == record['project_name']
    # Convert dicts to AlertPolicies.
    policies_json = [json.dumps(policy) for policy in record['policies']]
    policies = [google.protobuf.json_format.Parse(
        policy_json, monitoring_v3.types.alert_pb2.AlertPolicy())
        for policy_json in policies_json]
    # Convert dicts to NotificationChannels
    channels_json = [json.dumps(channel) for channel in record['channels']]
    channels = [google.protobuf.json_format.Parse(
        channel_json, monitoring_v3.types.notification_pb2.
        NotificationChannel()) 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.enums.NotificationChannel.\
            VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED

        if is_same_project:
            try:
                channel_client.update_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
            channel.ClearField("name")
            new_channel = channel_client.create_notification_channel(
                project_name, 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.
        policy.ClearField('creation_record')
        policy.ClearField('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(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
            policy.ClearField("name")
            for condition in policy.conditions:
                condition.ClearField("name")
            policy = alert_client.create_alert_policy(project_name, policy)
        print('Updated', policy.name)

Was this page helpful? Let us know how we did:

Send feedback about...

Stackdriver Monitoring