Remplacer les canaux de notification
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Explique comment remplacer les canaux de notification pour les règles d'alerte.
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],[],[],[],null,["# Replace notification channels\n\nDemonstrates how to replace notification channels across alerting policies.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Manage alerting policies by API](/monitoring/alerts/using-alerting-api)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n static void ReplaceChannels(string projectId, string alertPolicyId,\n IEnumerable\u003cstring\u003e channelIds)\n {\n var alertClient = AlertPolicyServiceClient.Create();\n var policy = new AlertPolicy()\n {\n Name = new AlertPolicyName(projectId, alertPolicyId).ToString()\n };\n foreach (string channelId in channelIds)\n {\n policy.NotificationChannels.Add(\n new NotificationChannelName(projectId, channelId)\n .ToString());\n }\n var response = alertClient.UpdateAlertPolicy(\n new FieldMask { Paths = { \"notification_channels\" } }, policy);\n Console.WriteLine(\"Updated {0}.\", response.Name);\n }\n\n### Go\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // replaceChannels replaces the notification channels in the alert policy\n // with channelIDs.\n func replaceChannels(w io.Writer, projectID, alertPolicyID string, channelIDs []string) error {\n \tctx := context.Background()\n\n \tclient, err := monitoring.NewAlertPolicyClient(ctx)\n \tif err != nil {\n \t\treturn err\n \t}\n \tdefer client.Close()\n\n \tpolicy := &monitoringpb.AlertPolicy{\n \t\tName: \"projects/\" + projectID + \"/alertPolicies/\" + alertPolicyID,\n \t}\n \tfor _, c := range channelIDs {\n \t\tc = \"projects/\" + projectID + \"/notificationChannels/\" + c\n \t\tpolicy.NotificationChannels = append(policy.NotificationChannels, c)\n \t}\n \treq := &monitoringpb.UpdateAlertPolicyRequest{\n \t\tAlertPolicy: policy,\n \t\tUpdateMask: &fieldmask.FieldMask{\n \t\t\tPaths: []string{\"notification_channels\"},\n \t\t},\n \t}\n \tif _, err := client.UpdateAlertPolicy(ctx, req); err != nil {\n \t\treturn fmt.Errorf(\"UpdateAlertPolicy: %w\", err)\n \t}\n \tfmt.Fprintf(w, \"Successfully replaced channels.\")\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n private static void replaceChannels(String projectId, String alertPolicyId, String[] channelIds)\n throws IOException {\n AlertPolicy.Builder policyBuilder =\n AlertPolicy.newBuilder().setName(AlertPolicyName.of(projectId, alertPolicyId).toString());\n for (String channelId : channelIds) {\n policyBuilder.addNotificationChannels(\n NotificationChannelName.of(projectId, channelId).toString());\n }\n try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {\n AlertPolicy result =\n client.updateAlertPolicy(\n FieldMask.newBuilder().addPaths(\"notification_channels\").build(),\n policyBuilder.build());\n System.out.println(String.format(\"Updated %s\", result.getName()));\n }\n }\n\n### Node.js\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Imports the Google Cloud client library\n const monitoring = require('https://cloud.google.com/nodejs/docs/reference/monitoring/latest/overview.html');\n\n // Creates clients\n const alertClient = new monitoring.https://cloud.google.com/nodejs/docs/reference/monitoring/latest/overview.html();\n const notificationClient = new monitoring.https://cloud.google.com/nodejs/docs/reference/monitoring/latest/overview.html();\n\n async function replaceChannels() {\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // const projectId = 'YOUR_PROJECT_ID';\n // const alertPolicyId = '123456789012314';\n // const channelIds = [\n // 'channel-1',\n // 'channel-2',\n // 'channel-3',\n // ];\n\n const notificationChannels = channelIds.map(id =\u003e\n notificationClient.projectNotificationChannelPath(projectId, id)\n );\n\n for (const channel of notificationChannels) {\n const updateChannelRequest = {\n updateMask: {\n paths: ['enabled'],\n },\n notificationChannel: {\n name: channel,\n enabled: {\n value: true,\n },\n },\n };\n try {\n await notificationClient.updateNotificationChannel(\n updateChannelRequest\n );\n } catch (err) {\n const createChannelRequest = {\n notificationChannel: {\n name: channel,\n notificationChannel: {\n type: 'email',\n },\n },\n };\n const newChannel =\n await notificationClient.createNotificationChannel(\n createChannelRequest\n );\n notificationChannels.push(newChannel);\n }\n }\n\n const updateAlertPolicyRequest = {\n updateMask: {\n paths: ['notification_channels'],\n },\n alertPolicy: {\n name: alertClient.projectAlertPolicyPath(projectId, alertPolicyId),\n notificationChannels: notificationChannels,\n },\n };\n const [alertPolicy] = await alertClient.updateAlertPolicy(\n updateAlertPolicyRequest\n );\n console.log(`Updated ${alertPolicy.name}.`);\n }\n replaceChannels();\n\n### PHP\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n use Google\\Cloud\\Monitoring\\V3\\AlertPolicy;\n use Google\\Cloud\\Monitoring\\V3\\Client\\AlertPolicyServiceClient;\n use Google\\Cloud\\Monitoring\\V3\\Client\\NotificationChannelServiceClient;\n use Google\\Cloud\\Monitoring\\V3\\UpdateAlertPolicyRequest;\n use Google\\Protobuf\\FieldMask;\n\n /**\n * @param string $projectId Your project ID\n * @param string $alertPolicyId Your alert policy id ID\n * @param string[] $channelIds array of channel IDs\n */\n function alert_replace_channels(string $projectId, string $alertPolicyId, array $channelIds): void\n {\n $alertClient = new AlertPolicyServiceClient([\n 'projectId' =\u003e $projectId,\n ]);\n\n $channelClient = new NotificationChannelServiceClient([\n 'projectId' =\u003e $projectId,\n ]);\n $policy = new AlertPolicy();\n $policy-\u003esetName($alertClient-\u003ealertPolicyName($projectId, $alertPolicyId));\n\n $newChannels = [];\n foreach ($channelIds as $channelId) {\n $newChannels[] = $channelClient-\u003enotificationChannelName($projectId, $channelId);\n }\n $policy-\u003esetNotificationChannels($newChannels);\n $mask = new FieldMask();\n $mask-\u003esetPaths(['notification_channels']);\n $updateAlertPolicyRequest = (new UpdateAlertPolicyRequest())\n -\u003esetAlertPolicy($policy)\n -\u003esetUpdateMask($mask);\n $updatedPolicy = $alertClient-\u003eupdateAlertPolicy($updateAlertPolicyRequest);\n printf('Updated %s' . PHP_EOL, $updatedPolicy-\u003egetName());\n }\n\n### Python\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def replace_notification_channels(project_name, alert_policy_id, channel_ids):\n \"\"\"Replace notification channel of an alert.\n\n Arguments:\n project_name (str): The Google Cloud Project to use. The project name\n must be in the format - 'projects/\u003cPROJECT_NAME\u003e'.\n alert_policy_id (str): The ID of the alert policy whose notification\n channels are to be replaced.\n channel_ids (str): ID of notification channel to be added as channel\n for the given alert policy.\n \"\"\"\n\n _, project_id = project_name.split(\"/\")\n alert_client = monitoring_v3.AlertPolicyServiceClient()\n channel_client = monitoring_v3.NotificationChannelServiceClient()\n policy = monitoring_v3.AlertPolicy()\n policy.name = alert_client.alert_policy_path(project_id, alert_policy_id)\n\n for channel_id in channel_ids:\n policy.notification_channels.append(\n channel_client.notification_channel_path(project_id, channel_id)\n )\n\n mask = field_mask.FieldMask()\n mask.paths.append(\"notification_channels\")\n updated_policy = alert_client.update_alert_policy(\n alert_policy=policy, update_mask=mask\n )\n print(\"Updated\", updated_policy.name)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=monitoring)."]]