CloudWatch Application Insights で重要度の高いアラートのみ通知してみた
こんにちは!クラウド事業本部コンサルティング部のたかくに(@takakuni_)です。
みなさん、CloudWatch Application Insights 使っていますでしょうか。
CloudWatch Alarm が自動で作成されて非常に便利ですよね。SNS トピックや EventBridge と統合することで通知もできちゃいます。
私も検証アカウントで有効にしているのですが、重要度が LOW の場合でも通知が飛んできているため、ノイズになりがちな印象です。
You are receiving this email because Problem "p-b09eb62c-1afc-4f16-aac7-fd18d192f481" has been RECURRING by Amazon CloudWatch Application Insights
Problem Details:
Problem URL: https://console.aws.amazon.com/cloudwatch/home?region=ap-northeast-1#settings:AppInsightsSettings/problemDetails?problemId=p-b09eb62c-1afc-4f16-aac7-fd18d192f481
Problem Summary: ALB: Backend 4XX errors
Severity: LOW
Insights: Target instances sent 4XX responses to the Application Load Balancer. If you configured your application to add your application error logs or access logs, view them to determine the cause of the error. Otherwise, view these logs on your instances. To view the responses, you can send requests directly to the instance, and by bypassing the load balancer.
Status: RECURRING
AffectedResource: arn:aws:elasticloadbalancing:ap-northeast-1:123456789012:loadbalancer/app/blue-green-lb/76b1efecb722d2d3
region: ap-northeast-1
RecurringCount: 10
StartTime: 2025-06-15T08:35:45Z
LastUpdatedTime: 2025-06-16T11:09:50.193Z
LastRecurrenceTime: 2025-06-16T11:09:50.193Z
今回は、この Applicationn Insights の Severity が Medium 以上だった場合に通知したいと思います。
Application Insights のメール通知について
Application Insights のメール通知には、大きく分けて 2 つの実装方式があります。
- EventBridge を利用した方法
- SNS へ直接通知を飛ばす方法
どちらがどのように異なるのでしょうか。違いを見てみましょう。
EventBridge を利用した方法
EventBridge を利用した方法では CloudWatch Application Insights において、問題が発生したタイミング(Application Insights Problem Detected
)と、その問題の状態が更新されたタイミング(Application Insights Problem Updated
)に通知を行います。
ここでいう、問題の状態とは以下のどれかを指します
IGNORE | RESOLVED | PENDING | RECURRING | RECOVERING
JSON 形式(構造化データ)で配信されるため、フィルターがかけやすいものの、ベストエフォートでの配信のため基本的には SNS 経由での配信が推奨されています。
{
"version": "0",
"account": "123456789012",
"region": "us-east-1",
"detail-type": "Application Insights Problem Detected",
"source": "aws.applicationinsights",
"time": "2016-06-30T22:06:31Z",
"id": "c071bfbf-83c4-49ca-a6ff-3df053957145",
"resources": [
"arn:aws:resource-groups:us-west-2:123456789012:group/MyExampleGroup",
"arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"
],
"detail": {
"problemId": "fndId",
"region": "us-east-1",
"resourceGroupName": "RG1",
"severity": "Low",
"status": "PENDING",
"problemUrl": "https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#home:AppInsights/fndId",
"opsItemArn": "arn:aws:sns:us-east-1:123456789012:mytopic",
"startTime": 1646282033864,
"updatedObservations": [
{
"id": "eve-1",
"startTime": 1646282033864,
"endTime": 1646302033864,
"observationType": "CLOUD_WATCH_EVENT"
},
{
"id": "eve-2",
"startTime": 1646282033864,
"endTime": 1646302033864,
"observationType": "CLOUD_WATCH_EVENT"
}
],
"lastUpdatedTime": 1646292033864,
"recurringCount": 1,
"lastRecurrenceTime": 1646292033864,
"affectedResource": "resource1",
"insights": ["insights"],
"ruleName": "ruleName1",
"endTime": 1646302033864
}
}
For each application that is added to CloudWatch Application Insights, a CloudWatch event is published for the following events on a best effort basis:
再掲:Application Insights CloudWatch Events for detected problems
SNS へ直接通知を飛ばす方法
つづいて、SNS へ直接通知を飛ばす方法です。
この方法は問題が作成、解決されたタイミング、新しい観測値が追加されたタイミングでメールが通知されます。
Amazon SNS 通知を設定すると、問題が作成または解決されたときに E メール通知が送信されます。また、新しい観測値が既存の問題に追加されると通知を受け取ります。
ベストエフォートではないものの、通知内容は非構造化データのため、SNS トピックのサブスクリプションフィルターで引っ掛けるのは難しそうです。
You are receiving this email because Problem "p-1234567" has been CREATED by Amazon CloudWatch Application Insights
Problem Details:
Problem URL: https:////console.aws.amazon.com/cloudwatch/home?region=us-east-1#settings:AppInsightsSettings/problemDetails?problemId=p-1234567
Problem Summary: Title of the problem
Severity: HIGH
Insights: Something specific is broken
Status : RESOLVED
AffectedResource: arn:aws:ec2:us-east-1:555555555555:host/testResource
Region: us-east-1
RecurringCount: 0
StartTime: 2019-03-23T10:42:57.777Z
LastUpdatedTime: 2019-03-23T21:49:37.777Z
LastRecurrenceTime:
StopTime: 2019-03-23T21:49:37.777Z
Recent Issues
- TelemetryArn:alarm1
StartTime: 2024-08-15T22:12:46.007Z
StopTime:
- TelemetryArn:log-group1
StartTime: 2024-08-15T22:12:46.007Z
StopTime: 2024-08-15T22:12:46.007Z
Receive notifications for detected problems
必ず配信したく、かつフィルターをかけたいため、今回は SNS + Lambda + SNS の構成で通知を実装してみたいと思います。
やってみた
Lambda
Lambda のコードは以下を利用しました。FILTERED_TOPIC_ARN
に環境変数を登録します。
severity を ['HIGH', 'MEDIUM']
で設定しているため、LOW だと、通知が飛ばないようにしています。
import json
import boto3
import re
import os
sns = boto3.client('sns')
# 環境変数から転送先のSNSトピックARNを取得
FILTERED_TOPIC_ARN = os.environ['FILTERED_TOPIC_ARN']
def lambda_handler(event, context):
try:
# SNSメッセージを取得
message = event['Records'][0]['Sns']['Message']
subject = event['Records'][0]['Sns'].get('Subject', 'CloudWatch Alert')
# Severityを抽出
severity_match = re.search(r'Severity:\s*(\w+)', message)
if not severity_match:
print("Severity not found in message")
return {
'statusCode': 200,
'body': json.dumps('Severity not found, message skipped')
}
severity = severity_match.group(1).upper()
# HIGH または MEDIUM の場合のみ転送
if severity in ['HIGH', 'MEDIUM']:
print(f"Forwarding {severity} severity alert")
# メッセージを転送
response = sns.publish(
TopicArn=FILTERED_TOPIC_ARN,
Message=message,
Subject=f'{subject} - Severity: {severity}'
)
return {
'statusCode': 200,
'body': json.dumps(f'Alert forwarded: {severity}')
}
else:
print(f"Skipping {severity} severity alert")
return {
'statusCode': 200,
'body': json.dumps(f'Alert skipped: {severity}')
}
except Exception as e:
print(f"Error processing message: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps(f'Error: {str(e)}')
}
監視してみた
Lambda を設定後、いくつか実行履歴が残っていますね。
LOW の場合
Lambda のログを見てみると LOW の場合、通知がスキップされていることがわかります。想定通りですね。
There are older events to load.
Load more.
INIT_START Runtime Version: python:3.12.v70 Runtime Version ARN: arn:aws:lambda:ap-northeast-1::runtime:b5ce413242a9b8ef00a46980d4de4b943c0679481f66d34d1a1dd06ad4e16fe8
START RequestId: 201b70a6-8b6c-42d9-b0cc-d4aefecfc494 Version: $LATEST
Skipping LOW severity alert
END RequestId: 201b70a6-8b6c-42d9-b0cc-d4aefecfc494
REPORT RequestId: 201b70a6-8b6c-42d9-b0cc-d4aefecfc494 Duration: 2.13 ms Billed Duration: 3 ms Memory Size: 128 MB Max Memory Used: 80 MB Init Duration: 426.33 ms
MEDIUM の場合
MEDIUM の場合、通知が走っていますね。Lambda 経由で SNS 通知が行われていますね。(Logger の書き方が Forwarding で少し雑ですが)
INIT_START Runtime Version: python:3.12.v70 Runtime Version ARN: arn:aws:lambda:ap-northeast-1::runtime:b5ce413242a9b8ef00a46980d4de4b943c0679481f66d34d1a1dd06ad4e16fe8
START RequestId: 1ba2f4ab-ed8f-4a7f-889f-37d9cc00beba Version: $LATEST
Forwarding MEDIUM severity alert
END RequestId: 1ba2f4ab-ed8f-4a7f-889f-37d9cc00beba
REPORT RequestId: 1ba2f4ab-ed8f-4a7f-889f-37d9cc00beba Duration: 287.19 ms Billed Duration: 288 ms Memory Size: 128 MB Max Memory Used: 82 MB Init Duration: 445.57 ms
最終的に、以下のイメージでメールが飛んできています。SNS トピックへ直接配信していた内容を、そのまま送信しています。
You are receiving this email because Problem "p-242cd08f-b6c4-4f6a-b61c-bcc318a720d8" has been CLOSED by Amazon CloudWatch Application Insights
Problem Details:
Problem URL: https://console.aws.amazon.com/cloudwatch/home?region=ap-northeast-1#settings:AppInsightsSettings/problemDetails?problemId=p-242cd08f-b6c4-4f6a-b61c-bcc318a720d8
Problem Summary: Resource bg-cluster: problem detected
Severity: MEDIUM
Insights:
Status: RESOLVED
AffectedResource: arn:aws:ecs:ap-northeast-1:123456789012:cluster/bg-cluster
region: ap-northeast-1
RecurringCount:
StartTime: 2025-06-18T16:59:40.372Z
LastUpdatedTime: 2025-06-18T18:52:42.363Z
LastRecurrenceTime:
StopTime: 2025-06-18T18:52:42.363Z
まとめ
以上、「CloudWatch Application Insights で重要度の高いアラートのみ通知してみた」でした。
Security Hub などであれば、スコア以上で実装はできるものの CloudWatch Application Insights は、ひと工夫が必要で勉強になりました。
クラウド事業本部コンサルティング部のたかくに(@takakuni_)でした!