Using Alarm Actions in Amazon CloudWatch

This Node.js code example shows:

How to change the state of your Amazon EC2 instances automatically based on a CloudWatch
alarm.

The Scenario

Using alarm actions, you can create alarms that automatically stop, terminate, reboot,
or recover your Amazon EC2 instances. You can use
the stop or terminate actions when you no longer need an instance to be running. You
can use the reboot and recover actions to
automatically reboot those instances.

In this example, a series of Node.js modules are used to define an alarm action in
CloudWatch that
triggers the reboot of an Amazon EC2 instance. The Node.js modules use the SDK for
JavaScript to manage Amazon EC2 instances using these methods of the
CloudWatch client class:

Creating and Enabling Actions on an Alarm

Create a Node.js module with the file name cw_enablealarmactions.js.
Be sure to configure the SDK as previously shown. To access CloudWatch, create an
AWS.CloudWatch service object.

Create a JSON object to hold the parameters for creating an alarm, specifying
ActionsEnabled as true and an array of ARNs for the actions the
alarm will trigger. Call the putMetricAlarm method of the
AWS.CloudWatch service object, which creates the alarm if it does not exist
or updates it if the alarm does exist.

In the callback function for the putMetricAlarm, upon successful completion create a JSON object
containing the name of the CloudWatch alarm. Call the enableAlarmActions method to enable the alarm action.

Disabling Actions on an Alarm

Create a Node.js module with the file name cw_disablealarmactions.js.
Be sure to configure the SDK as previously shown. To access CloudWatch, create an
AWS.CloudWatch service object. Create a JSON object containing the name of
the CloudWatch alarm. Call the disableAlarmActions method to disable the actions
for this alarm.