Solitary
Solitary

Reputation: 33

How to get specific value from CloudWatch Alarm with lambda(python)?

I want to monitor EC2 by using CloudWatch-SNS-lambda (python)-SNS-Email.

When I testing my python code, i find out that CW alarm "Message" contain escape processing that i cant get specific value from "Message".

I check the format of the alarm with code below.

from __future__ import print_function
import json
import boto3

def lambda_handler(event, context):
    subject = 'subject'
    Messagebody = event['Records'][0]['Sns']['Message']
    MY_SNS_TOPIC_ARN = 'XXXXXXXXXXXXXXXXXXXXXXXX'
    sns_client = boto3.client('sns')
    sns_client.publish(
        TopicArn = MY_SNS_TOPIC_ARN,
        Subject = subject,
        Message = Messagebody
   )

which find out "Message" contains escape processing.

      "Sns": {
        "Type": "Notification",
        "MessageId": "94be4651-8f2e-5039-9a4b-129fff80f9e8",
        "TopicArn": "XXXXXXXXXXXXXXXXXXXXXXX",
        "Subject": "ALARM: \"CPU_\" in Asia Pacific (Tokyo)",
        "Message": "{\"AlarmName\":\"TEST\",\"AlarmDescription\":\"TEST\",\"AWSAccountId\":\"XXXXXXXXXXX\",\"NewStateValue\":\"ALARM\",\"NewStateReason\":\"Threshold Crossed: 1 datapoint [64.633879781421 (01/02/19 15:56:00)] was greater than or equal to the threshold (40.0).\",\"StateChangeTime\":\"2019-02-01T16:06:06.908+0000\",\"Region\":\"Asia Pacific (Tokyo)\",\"OldStateValue\":\"OK\",\"Trigger\":{\"MetricName\":\"CPUUtilization\",\"Namespace\":\"AWS/EC2\",\"StatisticType\":\"Statistic\",\"Statistic\":\"AVERAGE\",\"Unit\":null,\"Dimensions\":[{\"value\":\"i-039c724383acd1a67\",\"name\":\"InstanceId\"}],\"Period\":300,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":40.0,\"TreatMissingData\":\"\",\"EvaluateLowSampleCountPercentile\":\"\"}}",
        "Timestamp": "2019-02-01T16:06:06.945Z",
        "SignatureVersion": "1",

I want to get value by using something like

MetricName = event['Records'][0]['Sns']['Message']["MetricName"]
How can i achieve this with python?

Upvotes: 1

Views: 1530

Answers (2)

Karthick Prabu
Karthick Prabu

Reputation: 39

To remove the escape-processing, you should do the following:

MessageBody = event['Records'][0]['Sns']['Message']

MessageBody = json.loads(MessageBody)

Then to access the Metric Name, you can do:

MetricName= event['Records'][0]['Sns']['Message']['Trigger']['MetricName']

Upvotes: 0

Milan Cermak
Milan Cermak

Reputation: 8074

The Message is a JSON string. You need to convert it to a Python dictionary first. Then, you can access its properties easily.

Messagebody = event['Records'][0]['Sns']['Message']
message_dict = json.loads(Messagebody)
metric_name = message_dict['Trigger']['MetricName']

Upvotes: 1

Related Questions