日本語

How to Test CloudWatch Alarms with AWS Emulator

​​AWS Emulator​Amazon CloudWatch,Amazon SNS,Amazon SQS,AWS CLI

With AWS Emulator running locally, you can send custom metrics to CloudWatch with the AWS CLI and exercise alarms without an AWS account. This article covers how to test a monitoring alarm that notifies you when the number of application errors exceeds a threshold, and how to test the code that receives that notification, on your local machine or in CI. It walks through sending metrics, retrieving statistics, the alarm entering ALARM, the notification arriving in an SQS queue from an SNS topic, and the alarm returning to OK. All commands and output are copied from the test environment.

Note

The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.556 (released November 21, 2026), AWS CLI 2.42.1, and jq 1.7. No AWS account or credentials were used. I did not verify how this behaves on real CloudWatch: pricing, how long it takes for metrics to appear in the list, when alarms are evaluated, email notifications, or permission checks. I also did not test high-resolution metrics (1-second granularity), get-metric-data with metric math, composite alarms, or --treat-missing-data values other than notBreaching. Statements about real AWS are based on the official documentation. The 12-digit account IDs in the output have been replaced.

Start the emulator and point the AWS CLI at it

AWS Emulator is an emulator that accepts AWS API calls on your own machine. According to the official documentation, you do not need an AWS account, and requests are not sent to AWS.

For installation, see the separate article "How to Get Started with AWS Emulator on Ubuntu". Here I installed the Debian package from the Linux instructions after verifying its signature with gpg. The commands below follow the official instructions. I was working as root, so I ran them without sudo.

bash
curl -fsSLO https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb
sudo apt-get install -y ./aws-emulator_amd64.deb

The command to start the emulator is aws-emulator. -t off turns off the usage data (telemetry) that is sent to AWS by default. The emulator keeps running in its terminal, so I used a separate terminal for the AWS CLI.

bash
aws-emulator -t off

In the terminal where you run the AWS CLI, set the environment variables from the official documentation. The emulator listens on 127.0.0.1:9297 and writes an access key, config files, and a certificate that are valid only for this run to ~/.aws/emulator/9297/.

bash
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
Warning

The official documentation warns that if you run a command in a shell where AWS_ENDPOINT_URL is not set, the command is sent to real AWS using whatever credentials it finds. On a machine that has real credentials, run commands only in a shell where all of the environment variables above are set.

If the end of the ARN is user/emulator, the emulator is responding. Right after startup, there are no metrics and no alarms.

text
$ aws sts get-caller-identity --query Arn --output text
arn:aws:iam::<12桁のアカウントID>:user/emulator
$ aws cloudwatch list-metrics
{
    "Metrics": []
}
$ aws cloudwatch describe-alarms
{
    "MetricAlarms": [],
    "CompositeAlarms": [],
    "LogAlarms": []
}

Send a custom metric

A CloudWatch metric is identified by a combination of namespace, metric name, and dimensions. According to the official glossary, a dimension is a name-value pair, and different value combinations are treated as different metrics. A namespace is a container that keeps your metrics separate from those of other applications.

Here I sent the number of errors (Errors) for a service named orders to the namespace Example/App. Values are sent with aws cloudwatch put-metric-data. I sent 3 and then 4 within the same minute. Neither call printed anything on success (the exit code was 0).

text
$ aws cloudwatch put-metric-data --namespace Example/App --metric-name Errors --dimensions Service=orders --value 3 --unit Count
$ aws cloudwatch put-metric-data --namespace Example/App --metric-name Errors --dimensions Service=orders --value 4 --unit Count

When you want to send several values in one request, such as response times, you can use Values and Counts. Values lists the values, and Counts lists how many times each value occurred. According to the put-metric-data reference, one request can send up to 150 distinct values per metric, and this form also lets you retrieve percentiles. In the latency.json below, 120 ms occurs once, 250 ms occurs twice, and 900 ms occurs once.

text
$ cat latency.json
[
  {
    "MetricName": "Latency",
    "Dimensions": [{"Name": "Service", "Value": "orders"}],
    "Values": [120, 250, 900],
    "Counts": [1, 2, 1],
    "Unit": "Milliseconds"
  }
]
$ aws cloudwatch put-metric-data --namespace Example/App --metric-data file://latency.json

You can confirm that two metrics were created with list-metrics. In the emulator, they appeared in the list immediately after sending. The put-metric-data reference says that on real CloudWatch, a new metric can take up to 15 minutes to appear in list-metrics.

text
$ aws cloudwatch list-metrics --namespace Example/App --query "Metrics[].[MetricName, Dimensions[0].Name, Dimensions[0].Value]" --output text
Errors	Service	orders
Latency	Service	orders

Retrieve statistics

You retrieve the sent values, grouped by period, with get-metric-statistics. --period 60 groups them by minute, and --statistics lists the statistics you want. For $START and $END, I used times 10 minutes ago and 5 minutes from now (values generated with something like date -u -d '-10 min' +%FT%TZ).

text
$ aws cloudwatch get-metric-statistics --namespace Example/App --metric-name Errors --dimensions Name=Service,Value=orders --start-time $START --end-time $END --period 60 --statistics Sum SampleCount Maximum
{
    "Label": "Errors",
    "Datapoints": [
        {
            "Timestamp": "2026-11-21T18:06:00+00:00",
            "SampleCount": 2.0,
            "Sum": 7.0,
            "Maximum": 4.0,
            "Unit": "Count"
        }
    ]
}

The 3 and 4 sent in the same minute were combined into one datapoint, with a sum (Sum) of 7 and a sample count (SampleCount) of 2. Timestamp is the start of the one-minute bucket.

Note that the dimension syntax differs from put-metric-data. put-metric-data takes Service=orders, while get-metric-statistics and put-metric-alarm below take Name=Service,Value=orders. The --dimensions description in the put-metric-data reference also points out this difference, using get-metric-data as an example.

I also retrieved the average, minimum, and maximum of Latency. The average of the four values (120, 250, 250, 900) is 380.

text
$ aws cloudwatch get-metric-statistics --namespace Example/App --metric-name Latency --dimensions Name=Service,Value=orders --start-time $START --end-time $END --period 60 --statistics SampleCount Average Minimum Maximum
{
    "Label": "Latency",
    "Datapoints": [
        {
            "Timestamp": "2026-11-21T18:06:00+00:00",
            "SampleCount": 4.0,
            "Average": 380.0,
            "Minimum": 120.0,
            "Maximum": 900.0,
            "Unit": "Milliseconds"
        }
    ]
}

Percentiles are specified with --extended-statistics, not --statistics. The median (p50) was 250, and p90 was 900.

text
$ aws cloudwatch get-metric-statistics --namespace Example/App --metric-name Latency --dimensions Name=Service,Value=orders --start-time $START --end-time $END --period 60 --extended-statistics p50 p90 --query "Datapoints[].ExtendedStatistics"
[
    {
        "p50": 250.0,
        "p90": 900.0
    }
]

Prepare the notification destination

Alarm notifications are sent to an SNS topic. So that I could inspect the contents of the notification during the test, I subscribed an SQS queue named alarm-inbox to an SNS topic named alarm-topic. As described in the SNS official documentation, the queue has a policy that allows messages from this topic. A detailed walkthrough of this setup is covered in the separate article "How to Deliver Messages from SNS to SQS with AWS Emulator".

text
$ aws sns create-topic --name alarm-topic --query TopicArn --output text
arn:aws:sns:us-east-1:<12桁のアカウントID>:alarm-topic
$ aws sqs create-queue --queue-name alarm-inbox --query QueueUrl --output text
https://sqs.us-east-1.amazonaws.com/<12-digit account ID>/alarm-inbox
$ aws sqs set-queue-attributes --queue-url $QURL --attributes file://queue-attrs.json
$ aws sns subscribe --topic-arn $TOPIC --protocol sqs --notification-endpoint $QARN --query SubscriptionArn --output text
arn:aws:sns:us-east-1:<12桁のアカウントID>:alarm-topic:<サブスクリプションID>

$TOPIC is the topic ARN, $QARN is the queue ARN, and $QURL is the queue URL. In queue-attrs.json, I put a policy that allows sqs:SendMessage for sns.amazonaws.com and restricts the source to $TOPIC. The ID at the end of the subscription ARN has been replaced. I created the file with jq as follows.

bash
jq -n --arg q "$QARN" --arg t "$TOPIC" '{Policy: ({Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:$q,Condition:{ArnEquals:{"aws:SourceArn":$t}}}]}|tojson)}' > queue-attrs.json

Create the alarm

You create an alarm with put-metric-alarm. Here I created an alarm named orders-errors-high that enters ALARM when the one-minute sum of Errors is 5 or more, and I configured it to notify alarm-topic both when it enters ALARM and when it returns to OK.

text
$ aws cloudwatch put-metric-alarm --alarm-name orders-errors-high --namespace Example/App --metric-name Errors --dimensions Name=Service,Value=orders --statistic Sum --period 60 --evaluation-periods 1 --threshold 5 --comparison-operator GreaterThanOrEqualToThreshold --treat-missing-data notBreaching --alarm-actions $TOPIC --ok-actions $TOPIC

According to the put-metric-alarm reference and the explanation of missing-data handling covered later, the options mean the following.

  • --statistic Sum --period 60: looks at the sum for each one-minute period
  • --evaluation-periods 1: evaluates using the most recent one period
  • --threshold 5 --comparison-operator GreaterThanOrEqualToThreshold: a value of 5 or more counts as breaching
  • --treat-missing-data notBreaching: a period with no data counts as not breaching
  • --alarm-actions, --ok-actions: the SNS topics to notify when the alarm enters ALARM or OK

If you omit --treat-missing-data, the default is missing. The missing-data explanation says notBreaching suits metrics that only have a value when an error occurs. The Errors metric here is meant to be that kind of metric, so I set notBreaching.

Right after creation, the state was INSUFFICIENT_DATA (not enough data to make a decision). The put-metric-alarm reference also says that a newly created alarm starts in INSUFFICIENT_DATA and is evaluated afterward.

text
$ aws cloudwatch describe-alarms --alarm-names orders-errors-high --query "MetricAlarms[0].{State: StateValue, Reason: StateReason, Statistic: Statistic, Period: Period, Threshold: Threshold, Operator: ComparisonOperator, TreatMissingData: TreatMissingData}"
{
    "State": "INSUFFICIENT_DATA",
    "Reason": "Unchecked: Initial alarm creation",
    "Statistic": "Sum",
    "Period": 60,
    "Threshold": 5.0,
    "Operator": "GreaterThanOrEqualToThreshold",
    "TreatMissingData": "notBreaching"
}

Crossing the threshold puts the alarm in ALARM and sends a notification

The emulator evaluated the alarm automatically. I issued no command to change its state. I checked the state every 5 seconds with describe-alarms. The alarm was created at 18:06:28, and it changed to ALARM right after 18:07. The time recorded in the alarm history was 18:07:00, because the minute of 18:06 (3 and 4, sum 7) was at or above the threshold of 5.

text
$ aws cloudwatch describe-alarms --alarm-names orders-errors-high --query "MetricAlarms[0].[StateValue, StateReason]" --output text
ALARM	Threshold Crossed: 1 out of the last 1 datapoints [7.0 (21/11/26 18:06:00)] was greater than or equal to the threshold (5.0) (minimum 1 datapoint for OK -> ALARM transition).

The notification had arrived in the SQS queue after passing through SNS. Below, jq extracts the main fields from the body (the JSON inside the SNS message). The subject (Subject) has the form ALARM: "alarm name" in region, and the body includes the previous and new states and the threshold settings.

text
$ aws sqs receive-message --queue-url $QURL --wait-time-seconds 5 --max-number-of-messages 10 --query "Messages[].Body" --output text | jq "{Subject, Message: (.Message | fromjson | {AlarmName, OldStateValue, NewStateValue, StateChangeTime, Trigger: {MetricName: .Trigger.MetricName, Statistic: .Trigger.Statistic, Threshold: .Trigger.Threshold}})}"
{
  "Subject": "ALARM: \"orders-errors-high\" in us-east-1",
  "Message": {
    "AlarmName": "orders-errors-high",
    "OldStateValue": "INSUFFICIENT_DATA",
    "NewStateValue": "ALARM",
    "StateChangeTime": "2026-11-21T18:07:00.277+0000",
    "Trigger": {
      "MetricName": "Errors",
      "Statistic": "SUM",
      "Threshold": 5.0
    }
  }
}

From data stopping to returning to OK

After that, I waited without sending any more metrics. Even with notBreaching set, the emulator's alarm did not return to OK right away in the minute after data stopped arriving. It stayed in ALARM at 18:08 and 18:09, and it became OK at 18:10:00. When I ran the same steps again, it likewise took three minutes from entering ALARM to returning to OK.

A timeline of alarm state changes by time. After sending 3 and 4 to Errors at 18:06:18, the alarm moved from INSUFFICIENT_DATA right after creation to ALARM at 18:07:00. Even without data, it stayed in ALARM for about three minutes, became OK at 18:10:00, went to ALARM at 18:11:08 via set-alarm-state, and returned to OK at 18:12:08. A notification arrived at each state change.
Times (UTC) when the alarm state changed in the test environment

According to the missing-data explanation, when CloudWatch evaluates an alarm, it retrieves data for more periods than --evaluation-periods (the evaluation range). If the evaluation range contains at least as many actual data points as --evaluation-periods, CloudWatch decides based on that data and does not use the missing-data setting. The same page also says that after a metric stops, the alarm may keep re-evaluating against the last data for a while. The emulator's output does not tell me whether the three-minute ALARM period came from this evaluation range.

The reason shown when it returned to OK was that a period with no data was treated as not breaching. Because I specified --ok-actions, the OK notification also arrived.

text
$ aws cloudwatch describe-alarms --alarm-names orders-errors-high --query "MetricAlarms[0].[StateValue, StateReason]" --output text
OK	Threshold Crossed: no datapoints were received for 1 period and 1 missing datapoint was treated as [NonBreaching].
$ aws sqs receive-message --queue-url $QURL --wait-time-seconds 5 --max-number-of-messages 10 --query "Messages[].Body" --output text | jq "{Subject, OldStateValue: (.Message | fromjson | .OldStateValue), NewStateValue: (.Message | fromjson | .NewStateValue)}"
{
  "Subject": "OK: \"orders-errors-high\" in us-east-1",
  "OldStateValue": "ALARM",
  "NewStateValue": "OK"
}

When you wait for state changes in a test, allow for these three minutes when you choose your wait time. If you only want to verify notifications, the set-alarm-state command below lets you skip producing data that crosses the threshold.

Verify notifications with set-alarm-state

If you only want to test the code that receives notifications, you do not need to produce data that crosses the threshold. According to the set-alarm-state reference, set-alarm-state temporarily changes an alarm's state for testing purposes, and when the state changes, a notification for that state is sent.

text
$ aws cloudwatch set-alarm-state --alarm-name orders-errors-high --state-value ALARM --state-reason "通知のテスト"
$ aws cloudwatch describe-alarms --alarm-names orders-errors-high --query "MetricAlarms[0].[StateValue, StateReason]" --output text
ALARM	通知のテスト
$ aws sqs receive-message --queue-url $QURL --wait-time-seconds 5 --max-number-of-messages 10 --query "Messages[].Body" --output text | jq "{Subject, NewStateReason: (.Message | fromjson | .NewStateReason)}"
{
  "Subject": "ALARM: \"orders-errors-high\" in us-east-1",
  "NewStateReason": "通知のテスト"
}

The text passed to --state-reason appeared unchanged as NewStateReason in the notification. In a test, you can use this to tell which notifications you triggered yourself.

The reference says that on real CloudWatch, the alarm often returns to its actual state within a few seconds. In the emulator, after I set it to ALARM at 18:11:08, it returned to OK at 18:12:08, one minute later. (The second run also took one minute.) Returning to OK also sends an OK notification, so if your test counts notifications, include this one as well.

Confirm state transitions in the history

With describe-alarm-history, you can see when the alarm's state changed and whether notifications were sent. --history-item-type StateUpdate filters to state changes only, and Action filters to actions such as notifications. The newest entries come first.

text
$ aws cloudwatch describe-alarm-history --alarm-name orders-errors-high --history-item-type StateUpdate --query "AlarmHistoryItems[].[Timestamp, HistorySummary]" --output text
2026-11-21T18:12:08.497000+00:00	Alarm updated from ALARM to OK
2026-11-21T18:11:08.496000+00:00	Alarm updated from OK to ALARM
2026-11-21T18:10:00.207000+00:00	Alarm updated from ALARM to OK
2026-11-21T18:07:00.277000+00:00	Alarm updated from INSUFFICIENT_DATA to ALARM
$ aws cloudwatch describe-alarm-history --alarm-name orders-errors-high --history-item-type Action --query "AlarmHistoryItems[].[Timestamp, HistorySummary]" --output text
2026-11-21T18:12:08.497000+00:00	Successfully executed action arn:aws:sns:us-east-1:<12桁のアカウントID>:alarm-topic
2026-11-21T18:11:08.496000+00:00	Successfully executed action arn:aws:sns:us-east-1:<12桁のアカウントID>:alarm-topic
2026-11-21T18:10:00.207000+00:00	Successfully executed action arn:aws:sns:us-east-1:<12桁のアカウントID>:alarm-topic
2026-11-21T18:07:00.277000+00:00	Successfully executed action arn:aws:sns:us-east-1:<12桁のアカウントID>:alarm-topic

The state changed four times, and the SNS notification succeeded each time. If a test does not behave as expected, check this history first to determine whether the state changed or whether the notification was sent, which narrows down the cause.

Finally, I deleted the alarm with delete-alarms, and the list returned to empty. According to the official limits description, the emulator keeps everything in memory and clears it when stopped. If you restart the emulator for each test run, you start from a state with no metrics and no alarms.

text
$ aws cloudwatch delete-alarms --alarm-names orders-errors-high
$ aws cloudwatch describe-alarms --query "MetricAlarms[].AlarmName"
[]

​Posted by 86