简体   繁体   中英

Stopping an AWS EC2 Instance with a Cloudwatch Alarm in Java

So far, I have set up an alarm in such a way:

dim = new Dimension()
        .withName("InstanceId")
        .withValue(hashedId);

alarmreq = new PutMetricAlarmRequest()
              .withDimensions(dim)
              .withMetricName(metricName)
              .withNamespace(nameSpace)
              .withAlarmName(alarmName)
              .withActionsEnabled(true)
              .withStatistic(statistic)
              .withThreshold(threshold)
              .withComparisonOperator("GreaterThanThreshold")
              .withPeriod(period)
              .withEvaluationPeriods(evaluationPeriods)
              .withAlarmActions("arn:aws:sns:us-west-2:xxxxxxxxx:NotifyMe");

gCloudWatch.putMetricAlarm(alarmreq);

This creates an alarm for the specified instance just fine that executes the SNS NotifyMe. However, I am unable to find any documentation on how to add to this alarm, or maybe the SNS, to Stop or Terminate the instance when the alarm goes to ALARM state.

The only leads I have is that although .withAlarmActions() only accepts an SNS or SQS action, SNS can make an HTTP request that I may be able to work with in the very worst case.

Also I know it is possible to add this functionality to an alarm because on the AWS web interface, you may create an alarm that stops or terminates the instance.

Found the answer through asking in the Amazon forums. Basically, I was wrong in the assumption that withAlarmActions only accepts SNS or SQS actions. It can also accept stop or terminate actions in the form of "arn:aws:automate:us-west-2:ec2:stop". The final line of code edited to be fixed would look like:

.withAlarmActions("arn:aws:sns:us-west-2:xxxxxxxxx:NotifyMe", "arn:aws:automate:us-west-2:ec2:stop");

Here is the full answer if anyone who is curious. https://forums.aws.amazon.com/thread.jspa?messageID=466061&#466061

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM