[英]AWS Lambda function + Cloudwatch, how to pass the right parameters to a timed execution
[英]Parse a CloudWatch alert in AWS Lambda Python function
我正在使用Lambda函數,該函數將基於CloudWatch警報執行一些操作。
警報的JSON格式為:
{
'SignatureVersion': '1',
'Timestamp': '2018-03-08T16: 06: 27.163Z',
'MessageId': 'df82d564-1651-5dc6-a37a-867f779226ec',
'Message': '{
"AlarmName": "awsec2-i-08c38bb8af7962797-CPU-Utilization",
"AlarmDescription": "Created from EC2 Console",
"AWSAccountId": "111111111111",
"NewStateValue": "ALARM",
"NewStateReason": "Threshold Crossed: 1 datapoint [1.49999999999939 (08/03/18 16:04:00)] was greater than or equal to the threshold (1.0).",
"StateChangeTime": "2018-03-08T16:06:27.124+0000",
"Region": "EU (Ireland)",
"OldStateValue": "OK",
"Trigger": {
"MetricName": "CPUUtilization",
"Namespace": "AWS/EC2",
"StatisticType": "Statistic",
"Statistic": "AVERAGE",
"Unit": null,
"Dimensions": [
{
"name": "InstanceId",
"value": "i-08c38bb8af7962797"
}
],
"Period": 60,
"EvaluationPeriods": 1,
"ComparisonOperator": "GreaterThanOrEqualToThreshold",
"Threshold": 1.0,
"TreatMissingData": "",
"EvaluateLowSampleCountPercentile": ""
}
}',
'Type': 'Notification',
'TopicArn': 'arn:aws:sns:eu-west-1: 11111111111:test',
'Subject': 'ALARM: "awsec2-i-08c38bb8af7962797-CPU-Utilization" in EU (Ireland)'
}
我需要了解的是如何告訴我的函數僅提取InstanceId
值,並將其用作該函數其余部分的變量。
Message
是作為字符串提供的JSON。 要訪問字符串的內容,您需要使用json.loads()
函數:
import json
alert = ... (from CloudWatch)
message = json.loads(alert['Message'])
[msg['value'] for msg in message['Trigger']['Dimensions'] if msg['name']=='InstanceId']
但是,請注意,這只會輸出作為警報的維度提供的InstanceId
。 並不是專門說這個實例引起了警報(但這是事實)。
例如,您可以基於一組 EC2實例創建警報。 如果平均CPU超過閾值,則會觸發警報。 但是,維將與組有關 ,而不是特定實例。
可以認為它是說“已觸發實例i-xxx篩選器的警報” ,而不是說“實例i-xxx觸發了警報” 。
只要您的警報始終基於單個實例,那么維度將是您期望的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.