LoginSignup
33
26

More than 5 years have passed since last update.

【AWS】LambdaのJSON入力と仲良くする(Python版)

Last updated at Posted at 2016-03-18

Lambdaのトリガーとなったイベントの情報を取得するにはJSONと仲良くする必要があります。
今回は、Lambdaに渡された情報を取得するための方法を見ていきます。


JSONの入力

Lambdaに渡されるJSONメッセージは全て event に格納されています。
デフォルトのLambda関数でよく

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


なんか書かれているのはそのためです。
ちゃんとメインの関数の入力にも event が指定されていますね。


基本

基本
event['要素名'][配列の要素番号]

このような形が基本です。
辞書型の”キー”を指定することで”値”を取得することができます。
また、配列になっている場合はその配列の"要素番号"を指定することで配列の要素を取得できます。


練習

[AWS]aws-cliでJSONを扱うためにーjq基本編ー
[AWS]aws-cliでJSONを扱うためにーjq基本編②ー←来週頭にアップします
で何度も使ったインスタンス情報を例に取って練習してみます。

このJSONがeventに格納されているとします。(一応最下段に置いておきます)

現在存在するインスタンスのインスタンスidを取得したい場合

インスタンスidの取得
InstanceId = event['Reservations'][n]['Instances']['InstanceId']

こんな形になります。
2つ目の[]の中の”n”に注目してください。
これはインスタンスの数だけ、インスタンス情報がReservations配列に格納されている事を意味します。
つまり、全てのインスタンスを精査したい場合などはfor文なんかを使ってぶん回してしまえば簡単に出来ます。

インスタンスidを取得し特定の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

こんな雰囲気で書いていけば動かせます。
とにかく必要な値をゴリゴリと削っていき、変数に格納する。
そいつを何らかの形で利用する!
ってシナリオが多いかと思います。


最近私は、stsと連携して全てのコンソリアカウント配下のインスタンス情報を精査し、特定の条件に一致したインスタンスが居た場合slackで通知するといったクーロンジョブを作ったり・・・なんてところで利用していたりします。
アカウント数、インスタンス数が多いとタイムアウトするのでその辺をどうするかをしっかり考えなければいけませんが、LambdaでJSONを使う場合とりあえずこんな感じで利用していけば使うことが出来ます。


サンプル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
                }
            ]
        }
    ]
}
33
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
26