Let's create an alarm and simulate the conditions that will trigger it by going through the following steps:
- We can create an alarm for a metric with the name FailedLogins and namespace ServerlessProgrammingCookbook as follows:
aws cloudwatch put-metric-alarm
--alarm-name FailedRequestsAlarm
--alarm-description 'Alarm for failed login requests'
--metric-name 'FailedLogins'
--namespace 'ServerlessProgrammingCookbook'
--statistic 'Average'
--period 60
--threshold 5
--comparison-operator GreaterThanOrEqualToThreshold
--evaluation-periods 1
--alarm-actions arn:aws:sns:us-east-1:<account id>:my-first-sns-topic
--region us-east-1
--profile admin
- Check the current status of the alarm using the describe-alarms command, as follows:
aws cloudwatch describe-alarms
--alarm-names FailedRequestsAlarm
--region us-east-1
--profile admin
If we try the describe-alarms command immediately after creation or if we have not sent any data for the metric within the specified period (60 seconds, in this case), we get the state INSUFFICIENT_DATA, as shown in the following screenshot:
- Send some data to the metric with matching dimensions (none in this case), using the following code:
aws cloudwatch put-metric-data
--namespace 'ServerlessProgrammingCookbook'
--metric-name 'FailedLogins'
--value 1
--region us-east-1
--profile admin
We need to wait for at least the period you mentioned (or some more time). The describe-alarms command output should contain the status OK, as shown in the following screenshot:
- Send data so that the average crosses the threshold (5, in our case) using the put-metric-data command. We will send a value of 10, as shown in the following code:
aws cloudwatch put-metric-data
--namespace 'ServerlessProgrammingCookbook'
--metric-name 'FailedLogins'
--value 10
--region us-east-1
--profile admin
If the SNS topic was configured correctly and we have subscribed to an email address successfully, we should get a message similar to the following:
The email will also contain the alarm details and state change action details, as shown in the following screenshot:
The change actions details are as follows:
When the average goes below the threshold, the alarm automatically goes back to the OK state.