Working with Amazon CloudWatch Alarms with AWS SDK for PHP Version 3
An Amazon CloudWatch alarm watches a single metric over a time period you specify. It performs one or more actions based on the value of the metric relative to a given threshold over a number of time periods.
The following examples show how to:
-
Describe an alarm using DescribeAlarms.
-
Create an alarm using PutMetricAlarm.
-
Delete an alarm using DeleteAlarms.
All the example code for the AWS SDK for PHP Version 3 is available here on GitHub.
Credentials
Before running the example code, configure your AWS credentials, as described in Credentials for the AWS SDK for PHP Version 3. Then import the AWS SDK for PHP, as described in Basic Usage Patterns of the AWS SDK for PHP Version 3.
Describe Alarms
Imports
require 'vendor/autoload.php'; use Aws\CloudWatch\CloudWatchClient; use Aws\Exception\AwsException;
Sample Code
$client = new Aws\CloudWatch\CloudWatchClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2010-08-01' ]); try { $result = $client->describeAlarms([ ]); foreach ($result['MetricAlarms'] as $alarm) { echo $alarm['AlarmName'] . "\n"; } } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Create an Alarm
Imports
require 'vendor/autoload.php'; use Aws\CloudWatch\CloudWatchClient; use Aws\Exception\AwsException;
Sample Code
$client = new Aws\CloudWatch\CloudWatchClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2010-08-01' ]); try { $result = $client->putMetricAlarm(array( // AlarmName is required 'AlarmName' => 'string', // MetricName is required 'MetricName' => 'string', // Namespace is required 'Namespace' => 'string', // Statistic is required //string: SampleCount | Average | Sum | Minimum | Maximum 'Statistic' => 'string', // Period is required 'Period' => integer, 'Unit' => 'Count/Second', // EvaluationPeriods is required 'EvaluationPeriods' => integer, // Threshold is required 'Threshold' => interger, // ComparisonOperator is required // string: GreaterThanOrEqualToThreshold | GreaterThanThreshold | LessThanThreshold | LessThanOrEqualToThreshold 'ComparisonOperator' => 'string', )); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Delete Alarms
Imports
require 'vendor/autoload.php'; use Aws\CloudWatch\CloudWatchClient; use Aws\Exception\AwsException;
Sample Code
$client = new Aws\CloudWatch\CloudWatchClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2010-08-01' ]); try { $result = $client->deleteAlarms([ 'AlarmNames' => [$alarmName] // REQUIRED ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }