通知チャンネルを置き換える
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
アラート ポリシー全体で通知チャンネルを置き換える方法を示します。
もっと見る
このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。
コードサンプル
C#
Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
Go
Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
Java
Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
Node.js
Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
PHP
Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
Python
Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","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)."]]