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

Viewed 18350

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"]
4 Answers

So, here's how I got the tags in my Python code for my Lambda function.

  ec2 = boto3.resource('ec2')
  instance = ec2.Instance(instanceId)

# get image_id from instance-id
  imageId = instance.image_id
  print(imageId)

  for tags in instance.tags:
    if tags["Key"] == 'Name':
      newName = tags["Value"] + ".mydomain.com"
  print(newName)

So, using instance.tags and then checking the "Key" matching my Name tags and pulling out the "Value" for creating the FQDN (Fully Qualified Domain Name).

Related