微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AWS Lambda python获取cloudwatch警报信息以向MS团队触发警报

如何解决AWS Lambda python获取cloudwatch警报信息以向MS团队触发警报

我设置了很少的云监视警报,一旦警报消失,就会触发lambda函数。在lambda中,我试图读取json并将其通知MS团队。但是我无法从基于json的位置获取警报名称

下面是json

{
  'Records': [
    {
      'EventSource': 'aws:sns','EventVersion': '1.0','EventSubscriptionArn': 'arn:aws:sns:ap-southeast-1:123:-teams-lambda-trigger:123-971d-4f70-927e-123','Sns': {
        'Type': 'Notification','MessageId': '12-d0b8-5a86-8b33-123','TopicArn': 'arn:aws:sns:ap-southeast-1:123:vip-prestogo-teams-lambda-trigger','Subject': 'ALARM: "AuthenticationFailedException-was101" in Asia Pacific (Singapore)','Message': '{"AlarmName":"AuthenticationFailedException-was101","AlarmDescription":"Found \\"AuthenticationFailedException\\" in 123","AWSAccountId":"123","NewStateValue":"ALARM","NewStateReason":"Threshold Crossed: 1 out of the last 1 datapoints [1.0 (30/08/20 07:38:00)] was greater than or equal to the threshold (-1.0) (minimum 1 datapoint for OK -> ALARM transition).","StateChangeTime":"2020-08-30T07:39:22.330+0000","Region":"Asia Pacific (Singapore)","AlarmArn":"arn:aws:cloudwatch:ap-southeast-1:123:alarm:AuthenticationFailedException-was101","OldStateValue":"OK","Trigger":{"MetricName":"AuthenticationFailedException-was101","Namespace":"AuthenticationFailedException-was101","StatisticType":"Statistic","Statistic":"AVERAGE","Unit":null,"Dimensions":[],"Period":60,"EvaluationPeriods":1,"Comparisonoperator":"GreaterThanorEqualToThreshold","Threshold":-1.0,"TreatMissingData":"- TreatMissingData:                    notBreaching","EvaluateLowSampleCountpercentile":""}}','Timestamp': '2020-08-30T07:39:22.372Z','Signatureversion': '1','Signature': '123/WJa6/3saRvSsz+eDW10LZaAlR7jMhnU4jE73UM/+123/123/123/123/123+j+pjE0nldGG+123/xouonYXLkBrfRQPtr1sv/RzrIJ/kTYr3EwSkGL032HNrOeWmdGZ9D4gIJ4ir/mbnbSZV7w==','SigningCertUrl': 'https://sns.ap-southeast-1.amazonaws.com/SimpleNotificationService.pem','UnsubscribeUrl': 'https://sns.ap-southeast-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-1:123:-teams-lambda-trigger:46235663-971d-4f70-927e-0a420040a154','MessageAttributes': {
          
        }
      }
    }
  ]
}

尝试如下,但失败:

 message = event['Records'][0]['Sns']['Message']
alarm =message['AlarmName']

我收到如下错误

字符串索引必须为整数:TypeError 追溯(最近一次通话): lambda_handler中的文件“ /var/task/lambda_function.py”,第15行 “文本”:event ['Records'] [0] ['Sns'] ['Message'] ['AlarmDescription'] TypeError:字符串索引必须为整数

请帮助

解决方法

您的event['Records'][0]['Sns']['Message'] json字符串,而不是python字典。您必须使用json.loads将其解析为字典:

import json # if not already present

message = json.loads(event['Records'][0]['Sns']['Message'])

alarm_name = message['AlarmName']
,

这是“ AlarmName”属性位于json字符串中的结果。您需要先对此进行解析,以便可以访问该属性。

使用json.parse函数来检索警报名称,如下面的示例Lambda函数。

import boto3
import json


def lambda_handler(event,context):
    message = event['Records'][0]['Sns']['Message']
    message = json.loads(message)
    alarm_name = message["AlarmName"]
    print(alarm_name)

我在Lambda中使用以下事件对此进行了测试

{
  "Records": [
    {
      "EventSource": "aws:sns","EventVersion": "1.0","EventSubscriptionArn": "arn:aws:sns:ap-southeast-1:123:-teams-lambda-trigger:123-971d-4f70-927e-123","Sns": {
        "Type": "Notification","MessageId": "12-d0b8-5a86-8b33-123","TopicArn": "arn:aws:sns:ap-southeast-1:123:vip-prestogo-teams-lambda-trigger","Subject": "ALARM: \"AuthenticationFailedException-was101\" in Asia Pacific (Singapore)","Message": "{\"AlarmName\":\"AuthenticationFailedException-was101\",\"AlarmDescription\":\"Found \\\"AuthenticationFailedException\\\" in 123\",\"AWSAccountId\":\"123\",\"NewStateValue\":\"ALARM\",\"NewStateReason\":\"Threshold Crossed: 1 out of the last 1 datapoints [1.0 (30/08/20 07:38:00)] was greater than or equal to the threshold (-1.0) (minimum 1 datapoint for OK -> ALARM transition).\",\"StateChangeTime\":\"2020-08-30T07:39:22.330+0000\",\"Region\":\"Asia Pacific (Singapore)\",\"AlarmArn\":\"arn:aws:cloudwatch:ap-southeast-1:123:alarm:AuthenticationFailedException-was101\",\"OldStateValue\":\"OK\",\"Trigger\":{\"MetricName\":\"AuthenticationFailedException-was101\",\"Namespace\":\"AuthenticationFailedException-was101\",\"StatisticType\":\"Statistic\",\"Statistic\":\"AVERAGE\",\"Unit\":null,\"Dimensions\":[],\"Period\":60,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":-1.0,\"TreatMissingData\":\"- TreatMissingData:                    notBreaching\",\"EvaluateLowSampleCountPercentile\":\"\"}}","Timestamp": "2020-08-30T07:39:22.372Z","SignatureVersion": "1","Signature": "123/WJa6/3saRvSsz+eDW10LZaAlR7jMhnU4jE73UM/+123/123/123/123/123+j+pjE0nldGG+123/xouonYXLkBrfRQPtr1sv/RzrIJ/kTYr3EwSkGL032HNrOeWmdGZ9D4gIJ4ir/mbnbSZV7w==","SigningCertUrl": "https://sns.ap-southeast-1.amazonaws.com/SimpleNotificationService.pem","UnsubscribeUrl": "https://sns.ap-southeast-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-1:123:-teams-lambda-trigger:46235663-971d-4f70-927e-0a420040a154","MessageAttributes": {
          
        }
      }
    }
  ]
}

此Lambda函数输出字符串AuthenticationFailedException-was101

,

message = event ['Records'] [0] ['Sns'] ['Message'],您的消息是一个字符串,需要将其转换为字典。每当您对此有疑问时,都可以使用print(type(variable_name))。您的message值可能具有也可能没有该特定键,因此可以使用get()函数来检索该值。

import json 
message = json.loads(event['Records'][0]['Sns']['Message'])
alarm_name = message.get('AlarmName',None)
if alarm_name not None:
   {your action}
else:
    {some default action when key not present}
   

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。