使用 Amazon 开发工具包启用 CloudWatch 告警操作 - Amazon CloudWatch
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包启用 CloudWatch 告警操作

以下代码示例展示如何启用 Amazon CloudWatch 告警操作。

.NET
Amazon SDK for .NET

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.CloudWatch; using Amazon.CloudWatch.Model; /// <summary> /// This example shows how to enable the Amazon CloudWatch actions for /// one or more CloudWatch alarms. The example was created using the /// AWS SDK for .NET version 3.7 and .NET Core 5.0. /// </summary> public class EnableAlarmActions { public static async Task Main() { IAmazonCloudWatch cwClient = new AmazonCloudWatchClient(); var alarmNames = new List<string> { "ALARM_NAME", "ALARM_NAME_2", }; var success = await EnableAlarmActionsAsync(cwClient, alarmNames); if (success) { Console.WriteLine("Alarm action(s) successfully enabled."); } else { Console.WriteLine("Alarm action(s) were not enabled.") } } /// <summary> /// Enable the actions for the list of CloudWatch alarm names passed /// in the alarmNames parameter. /// </summary> /// <param name="client">An initialized CloudWatch client object.</param> /// <param name="alarmNames">The list of CloudWatch alarms to enable.</param> /// <returns>A Boolean value indicating the success of the call.</returns> public static async Task<bool> EnableAlarmActionsAsync(IAmazonCloudWatch client, List<string> alarmNames) { var request = new EnableAlarmActionsRequest { AlarmNames = alarmNames, }; var response = await client.EnableAlarmActionsAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 EnableAlarmActions

Java
SDK for Java 2.x

public static void enableActions(CloudWatchClient cw, String alarm) { try { EnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder() .alarmNames(alarm).build(); cw.enableAlarmActions(request); System.out.printf( "Successfully enabled actions on alarm %s", alarm); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 EnableAlarmActions

JavaScript
SDK for JavaScript V3

在单独的模块中创建客户端并将其导出。

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon CloudWatch service client object. export const cwClient = new CloudWatchClient({ region: REGION });

导入开发工具包和客户端模块,然后调用 API。

// Import required AWS SDK clients and commands for Node.js import { PutMetricAlarmCommand, EnableAlarmActionsCommand, } from "@aws-sdk/client-cloudwatch"; import { cwClient } from "./libs/cloudWatchClient.js"; // Set the parameters export const params = { AlarmName: "ALARM_NAME", //ALARM_NAME ComparisonOperator: "GreaterThanThreshold", EvaluationPeriods: 1, MetricName: "CPUUtilization", Namespace: "AWS/EC2", Period: 60, Statistic: "Average", Threshold: 70.0, ActionsEnabled: true, AlarmActions: ["ACTION_ARN"], //e.g., "arn:aws:automate:us-east-1:ec2:stop" AlarmDescription: "Alarm when server CPU exceeds 70%", Dimensions: [ { Name: "InstanceId", Value: "INSTANCE_ID", }, ], Unit: "Percent", }; export const run = async () => { try { const data = await cwClient.send(new PutMetricAlarmCommand(params)); console.log("Alarm action added; RequestID:", data); return data; const paramsEnableAlarmAction = { AlarmNames: [params.AlarmName], }; try { const data = await cwClient.send( new EnableAlarmActionsCommand(paramsEnableAlarmAction) ); console.log("Alarm action enabled; RequestID:", data.$metadata.requestId); } catch (err) { console.log("Error", err); return data; } } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run();
SDK for JavaScript V2

导入开发工具包和客户端模块,然后调用 API。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create CloudWatch service object var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); var params = { AlarmName: 'Web_Server_CPU_Utilization', ComparisonOperator: 'GreaterThanThreshold', EvaluationPeriods: 1, MetricName: 'CPUUtilization', Namespace: 'AWS/EC2', Period: 60, Statistic: 'Average', Threshold: 70.0, ActionsEnabled: true, AlarmActions: ['ACTION_ARN'], AlarmDescription: 'Alarm when server CPU exceeds 70%', Dimensions: [ { Name: 'InstanceId', Value: 'INSTANCE_ID' }, ], Unit: 'Percent' }; cw.putMetricAlarm(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Alarm action added", data); var paramsEnableAlarmAction = { AlarmNames: [params.AlarmName] }; cw.enableAlarmActions(paramsEnableAlarmAction, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Alarm action enabled", data); } }); } });
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

suspend fun enableActions(alarm: String) { val request = EnableAlarmActionsRequest { alarmNames = listOf(alarm) } CloudWatchClient { region = "us-east-1" }.use { cwClient -> cwClient.enableAlarmActions(request) println( "Successfully enabled actions on alarm $alarm") } }
Python
适用于 Python (Boto3) 的 SDK

class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def enable_alarm_actions(self, alarm_name, enable): """ Enables or disables actions on the specified alarm. Alarm actions can be used to send notifications or automate responses when an alarm enters a particular state. :param alarm_name: The name of the alarm. :param enable: When True, actions are enabled for the alarm. Otherwise, they disabled. """ try: alarm = self.cloudwatch_resource.Alarm(alarm_name) if enable: alarm.enable_actions() else: alarm.disable_actions() logger.info( "%s actions for alarm %s.", "Enabled" if enable else "Disabled", alarm_name) except ClientError: logger.exception( "Couldn't %s actions alarm %s.", "enable" if enable else "disable", alarm_name) raise

有关 Amazon 开发工具包开发人员指南和代码示例的完整列表,包括帮助入门和有关早期版本的信息,请参阅 将 CloudWatch 与 Amazon 开发工具包结合使用