[AWS] Make friends with Lambda's JSON input (Python version)

You need to get along with JSON to get information about the event that triggered Lambda. This time, we'll look at how to get the information passed to Lambda.


JSON input

All JSON messages passed to Lambda are stored in event. The default Lambda function is fine

sample


def lambda_handler(event, context):
	message = event["Message"][0]["hoge"]
	
	

That's why something is written. Event is also specified in the input of the main function properly.


Basic

Basic


event['Element name'][Array element number]

This is the basic shape. You can get the "value" by specifying the dictionary type "key". Also, if it is an array, you can get the elements of the array by specifying the "element number" of the array.


practice

[AWS] To handle JSON with aws-cli-jq basics- [AWS] To handle JSON with aws-cli-jq basics ②- ← Will be uploaded at the beginning of next week Let's practice by taking the instance information used many times in.

Suppose this JSON is stored in event. (I will put it at the bottom for the time being)

If you want to get the instance id of the currently existing instance

Get instance id


InstanceId = event['Reservations'][n]['Instances']['InstanceId']

It looks like this. Notice the "n" in the second []. This means that as many instance information as there are instances are stored in the Reservations array. In other words, if you want to scrutinize all the instances, you can easily do it by using a for statement or something.

A function that gets an instance id and checks if it matches a specific id


TARGET_INSTANE_ID = 'i-********'

def check_instance_id(TARGET_INSTANE_ID): 
	event_msg = event['Reservations']
	count = len(event_msg)
	
	for n in range(0,count):
		InstanceId = event['Reservations'][n]['Instances']['InstanceId']
		if InstanceId == TARGET_INSTANE_ID:
			msg = "OK"
		else:
			msg = "NG"
			
		print(msg)
		
		return msg
		

If you write in such an atmosphere, you can move it. Anyway, scrape the necessary values and store them in variables. Use it in some way! I think there are many scenarios.


__ Recently, I have collaborated with sts to scrutinize the instance information under all consolidator accounts, and create a coulomb job such as notifying with slack when there is an instance that matches a specific condition. I'm doing it. __ If there are many accounts and instances, it will time out, so you have to think about what to do about it, but when using JSON with Lambda, you can use it like this for the time being.


Sample JSON

{
    "Reservations": [
        {
            "OwnerId": "************", 
            "ReservationId": "r-********", 
            "Groups": [], 
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    }, 
                    "PublicDnsName": "ec2-*************.ap-northeast-1.compute.amazonaws.com", 
                    "State": {
                        "Code": 16, 
                        "Name": "running"
                    }, 
                    "EbsOptimized": false, 
                    "LaunchTime": "2016-03-08T08:25:51.000Z", 
                    "PublicIpAddress": "************", 
                    "PrivateIpAddress": "172.31.23.149", 
                    "ProductCodes": [], 
                    "VpcId": "vpc-********", 
                    "StateTransitionReason": "", 
                    "InstanceId": "i-********", 
                    "ImageId": "ami-59bdb937", 
                    "PrivateDnsName": "ip-172-31-23-149.ap-northeast-1.compute.internal", 
                    "KeyName": "ec2kye", 
                    "SecurityGroups": [
                        {
                            "GroupName": "launch-wizard-4", 
                            "GroupId": "sg-********"
                        }
                    ], 
                    "ClientToken": "AKWfs123456789", 
                    "SubnetId": "subnet-********", 
                    "InstanceType": "t2.micro", 
                    "NetworkInterfaces": [
                        {
                            "Status": "in-use", 
                            "MacAddress": "06:e4:22:c1:df:c5", 
                            "SourceDestCheck": true, 
                            "VpcId": "vpc-********", 
                            "Description": "", 
                            "Association": {
                                "PublicIp": "*************", 
                                "PublicDnsName": "ec2-*********.ap-northeast-1.compute.amazonaws.com", 
                                "IpOwnerId": "amazon"
                            }, 
                            "NetworkInterfaceId": "eni-********", 
                            "PrivateIpAddresses": [
                                {
                                    "PrivateDnsName": "ip-172-31-23-149.ap-northeast-1.compute.internal", 
                                    "Association": {
                                        "PublicIp": "************", 
                                        "PublicDnsName": "ec2-***********.ap-northeast-1.compute.amazonaws.com", 
                                        "IpOwnerId": "amazon"
                                    }, 
                                    "Primary": true, 
                                    "PrivateIpAddress": "172.31.23.149"
                                }
                            ], 
                            "PrivateDnsName": "ip-172-31-23-149.ap-northeast-1.compute.internal", 
                            "Attachment": {
                                "Status": "attached", 
                                "DeviceIndex": 0, 
                                "DeleteOnTermination": true, 
                                "AttachmentId": "eni-attach-*********", 
                                "AttachTime": "2016-03-08T08:25:51.000Z"
                            }, 
                            "Groups": [
                                {
                                    "GroupName": "launch-wizard-1", 
                                    "GroupId": "sg-*********"
                                }
                            ], 
                            "SubnetId": "subnet-*************", 
                            "OwnerId": "************", 
                            "PrivateIpAddress": "172.31.23.149"
                        }
                    ], 
                    "SourceDestCheck": true, 
                    "Placement": {
                        "Tenancy": "default", 
                        "GroupName": "", 
                        "AvailabilityZone": "ap-northeast-1a"
                    }, 
                    "Hypervisor": "xen", 
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/xvda", 
                            "Ebs": {
                                "Status": "attached", 
                                "DeleteOnTermination": true, 
                                "VolumeId": "vol-**********", 
                                "AttachTime": "2016-03-08T08:25:52.000Z"
                            }
                        }
                    ], 
                    "Architecture": "x86_64", 
                    "RootDeviceType": "ebs", 
                    "RootDeviceName": "/dev/xvda", 
                    "VirtualizationType": "hvm", 
                    "AmiLaunchIndex": 0
                }
            ]
        }, 
        {
            "OwnerId": "**************", 
            "ReservationId": "r-**********", 
            "Groups": [], 
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    }, 
                    "PublicDnsName": "", 
                    "Platform": "windows", 
                    "State": {
                        "Code": 80, 
                        "Name": "stopped"
                    }, 
                    "EbsOptimized": false, 
                    "LaunchTime": "2016-02-24T05:53:59.000Z", 
                    "PrivateIpAddress": "172.31.31.197", 
                    "ProductCodes": [], 
                    "VpcId": "vpc-c**********", 
                    "StateTransitionReason": "User initiated (2016-02-24 10:01:43 GMT)", 
                    "InstanceId": "i-**********", 
                    "ImageId": "ami-2044434e", 
                    "PrivateDnsName": "ip-172-31-31-197.ap-northeast-1.compute.internal", 
                    "KeyName": "macpro", 
                    "SecurityGroups": [
                        {
                            "GroupName": "RDP", 
                            "GroupId": "sg-**********"
                        }
                    ], 
                    "ClientToken": "rduVq123456789", 
                    "SubnetId": "subnet-*********", 
                    "InstanceType": "t2.micro", 
                    "NetworkInterfaces": [
                        {
                            "Status": "in-use", 
                            "MacAddress": "06:34:e3:b1:a2:0d", 
                            "SourceDestCheck": true, 
                            "VpcId": "vpc-********", 
                            "Description": "", 
                            "NetworkInterfaceId": "eni-**********", 
                            "PrivateIpAddresses": [
                                {
                                    "PrivateDnsName": "ip-172-31-31-197.ap-northeast-1.compute.internal", 
                                    "Primary": true, 
                                    "PrivateIpAddress": "172.31.31.197"
                                }
                            ], 
                            "PrivateDnsName": "ip-172-31-31-197.ap-northeast-1.compute.internal", 
                            "Attachment": {
                                "Status": "attached", 
                                "DeviceIndex": 0, 
                                "DeleteOnTermination": true, 
                                "AttachmentId": "eni-attach-********", 
                                "AttachTime": "2016-02-24T05:53:59.000Z"
                            }, 
                            "Groups": [
                                {
                                    "GroupName": "RDP", 
                                    "GroupId": "sg-**********"
                                }
                            ], 
                            "SubnetId": "subnet-*********", 
                            "OwnerId": "************", 
                            "PrivateIpAddress": "172.31.31.197"
                        }
                    ], 
                    "SourceDestCheck": true, 
                    "Placement": {
                        "Tenancy": "default", 
                        "GroupName": "", 
                        "AvailabilityZone": "ap-northeast-1a"
                    }, 
                    "Hypervisor": "xen", 
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/sda1", 
                            "Ebs": {
                                "Status": "attached", 
                                "DeleteOnTermination": true, 
                                "VolumeId": "vol-**********", 
                                "AttachTime": "2016-02-24T05:54:04.000Z"
                            }
                        }
                    ], 
                    "Architecture": "x86_64", 
                    "StateReason": {
                        "Message": "Client.UserInitiatedShutdown: User initiated shutdown", 
                        "Code": "Client.UserInitiatedShutdown"
                    }, 
                    "RootDeviceName": "/dev/sda1", 
                    "VirtualizationType": "hvm", 
                    "RootDeviceType": "ebs", 
                    "Tags": [
                        {
                            "Value": "test", 
                            "Key": "Name"
                        }
                    ], 
                    "AmiLaunchIndex": 0
                }
            ]
        }
    ]
}

Recommended Posts

[AWS] Make friends with Lambda's JSON input (Python version)
Make JSON into CSV with Python from Splunk
[Python] Use JSON with Python
AWS CDK with Python
Check version with python
Make ordinary tweets fleet-like with AWS Lambda and Python
POST json with Python3 script
Make Puyo Puyo AI with Python
Make a fortune with Python
Specify python version with virtualenv
Format json with Vim (with python)
Read json data with python
[Python] Make AWS resources mocked with Moto into pytest fixtures
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
Make Echolalia LINEbot with Python + heroku
Matrix representation with Python standard input
Let's make a GUI with python.
Text extraction with AWS Textract (Python3.6)
Input / output with Python (Python learning memo ⑤)
JSON encoding and decoding with python
Make a recommender system with python
Make a scraping app with Python + Django + AWS and change jobs
Manage each Python version with Homebrew
Let's make a graph with python! !!
Notify HipChat with AWS Lambda (Python)
Let's make a web chat using WebSocket with AWS serverless (Python)!
[AWS SAM] Introduction to Python version
[Python Windows] pip install with Python version
[AWS] [GCP] I tried to make cloud services easy to use with Python
[AWS] Using ini files with Lambda [Python]
Data input / output in Python (CSV, JSON)
Convert Excel data to JSON with python
Fractal to make and play with Python
Let's make a voice slowly with Python
I want to play with aws with python
Make pypy submission easier with atcoder-cli (python)
Reading and writing JSON files with Python
[Python] Let's make matplotlib compatible with Japanese
Connect to s3 with AWS Lambda Python
Let's make a web framework with Python! (1)
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
Touch AWS with Serverless Framework and Python
Python + Selenium + Headless Chromium with aws lambda
Python #JSON
Make Python scripts into Windows-executable .exes with Pyinstaller
[2020 version] How to install Python3 on AWS EC2
Make a Twitter trend bot with heroku + Python
[Python] Make a game with Pyxel-Use an editor-
Read JSON with Python and output as CSV
I want to make a game with Python
Manage Python multiple version environment with Pythonz, virtualenv
Try to make a "cryptanalysis" cipher with Python
LINE BOT with Python + AWS Lambda + API Gateway
Make your own module quickly with setuptools (python)
[Python] Make a simple maze game with Pyxel
Serverless application with AWS SAM! (APIGATEWAY + Lambda (Python))
[Rust / Python] Handle numpy with PyO3 (August 2020 version)
[Improved version] Script to monitor CPU with Python
Manage AWS nicely with the Python library Boto