搭EnableAlarmActions配 AWS SDK或使用 CLI - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

EnableAlarmActions配 AWS SDK或使用 CLI

下列程式碼範例會示範如何使用EnableAlarmActions

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Enable the actions for a list of alarms from CloudWatch. /// </summary> /// <param name="alarmNames">A list of names of alarms.</param> /// <returns>True if successful.</returns> public async Task<bool> EnableAlarmActions(List<string> alarmNames) { var enableAlarmActionsResult = await _amazonCloudWatch.EnableAlarmActionsAsync( new EnableAlarmActionsRequest() { AlarmNames = alarmNames }); return enableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK; }
C++
SDK對於 C ++
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

包括必需的檔案。

#include <aws/core/Aws.h> #include <aws/monitoring/CloudWatchClient.h> #include <aws/monitoring/model/EnableAlarmActionsRequest.h> #include <aws/monitoring/model/PutMetricAlarmRequest.h> #include <iostream>

啟用警示動作。

Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::PutMetricAlarmRequest request; request.SetAlarmName(alarm_name); request.SetComparisonOperator( Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold); request.SetEvaluationPeriods(1); request.SetMetricName("CPUUtilization"); request.SetNamespace("AWS/EC2"); request.SetPeriod(60); request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average); request.SetThreshold(70.0); request.SetActionsEnabled(false); request.SetAlarmDescription("Alarm when server CPU exceeds 70%"); request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds); request.AddAlarmActions(actionArn); Aws::CloudWatch::Model::Dimension dimension; dimension.SetName("InstanceId"); dimension.SetValue(instanceId); request.AddDimensions(dimension); auto outcome = cw.PutMetricAlarm(request); if (!outcome.IsSuccess()) { std::cout << "Failed to create CloudWatch alarm:" << outcome.GetError().GetMessage() << std::endl; return; } Aws::CloudWatch::Model::EnableAlarmActionsRequest enable_request; enable_request.AddAlarmNames(alarm_name); auto enable_outcome = cw.EnableAlarmActions(enable_request); if (!enable_outcome.IsSuccess()) { std::cout << "Failed to enable alarm actions:" << enable_outcome.GetError().GetMessage() << std::endl; return; } std::cout << "Successfully created alarm " << alarm_name << " and enabled actions on it." << std::endl;
CLI
AWS CLI

啟用警示的所有動作

下列範例使用 enable-alarm-actions 命令來啟用名為 myalarm 之警示的所有動作:

aws cloudwatch enable-alarm-actions --alarm-names myalarm

如果成功,此命令會回到提示字元。

Java
SDK對於爪哇 2.x
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatch.model.EnableAlarmActionsRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class EnableAlarmActions { public static void main(String[] args) { final String usage = """ Usage: <alarmName> Where: alarmName - An alarm name to enable (for example, MyAlarm). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String alarm = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() .region(region) .build(); enableActions(cw, alarm); cw.close(); } 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); } } }
  • 如需詳API細資訊,請參閱AWS SDK for Java 2.x API參考EnableAlarmActions中的。

JavaScript
SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

匯入SDK和用戶端模組並呼叫API.

import { EnableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch"; import { client } from "../libs/client.js"; const run = async () => { const command = new EnableAlarmActionsCommand({ AlarmNames: [process.env.CLOUDWATCH_ALARM_NAME], // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm. }); try { return await client.send(command); } catch (err) { console.error(err); } }; export default run();

在單獨的模組中建立用戶端並將其匯出。

import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; export const client = new CloudWatchClient({});
SDK對於 JavaScript (第 2 個)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

匯入SDK和用戶端模組並呼叫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對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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") } }
  • 有API關詳細資訊,請參閱EnableAlarmActionsAWS SDK的以取得 Kotlin API 的參考資料

Python
SDK對於 Python(肉毒桿菌 3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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
  • 如需詳API細資訊,請參閱EnableAlarmActionsAWS SDK的《Python (博多 3) API 參考》。

SAP ABAP
SDK對於 SAP ABAP
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

"Enable actions on the specified alarm." TRY. lo_cwt->enablealarmactions( it_alarmnames = it_alarm_names ). MESSAGE 'Alarm actions enabled.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.
  • 如需詳API細資訊,請參閱EnableAlarmActionsAWS SDK的以供SAPABAPAPI參考