How to access the event object with python in AWS Lambda?

Chrisjx picture Chrisjx · Sep 14, 2017 · Viewed 12.9k times · Source

To follow up on this question: Filter CloudWatch Logs to extract Instance ID

I think it leaves the question incomplete because it does not say how to access the event object with python.

My goal is to:

  • read the instance that was triggered by a change in running state
  • get a tag value associated with the instance
  • start all other instances that have the same tag

The Cloudwatch trigger event is:

{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}

I can see examples like this:

def lambda_handler(event, context):

    # here I want to get the instance tag value
    # and set the tag filter based on the instance that 
    # triggered the event

    filters = [{
            'Name': 'tag:StartGroup',
            'Values': ['startgroup1'] 
        },
        {
            'Name': 'instance-state-name', 
            'Values': ['running']
        }
    ]

    instances = ec2.instances.filter(Filters=filters)

I can see the event object but I don't see how to drill down into the tag of the instance that had it's state changed to running.

Please, what is the object attribute through which I can get a tag from the triggered instance?

I suspect it is something like:

myTag = event.details.instance-id.tags["startgroup1"]

Answer

Vaisakh PS picture Vaisakh PS · Sep 14, 2017

In the Details Section of the Event, you will get the instance Id's. Using the instance id and AWS SDK you can query the tags. The following is the sample event

{
  "version": "0",
  "id": "ee376907-2647-4179-9203-343cfb3017a4",
  "detail-type": "EC2 Instance State-change Notification",
  "source": "aws.ec2",
  "account": "123456789012",
  "time": "2015-11-11T21:30:34Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"
  ],
  "detail": {
    "instance-id": "i-abcd1111",
    "state": "running"
  }
}