pythonjsonlambdaamazon-cloudtrail

getting [ERROR] IndexError: list index out of range in lambda while trying to fetch InstanceId from RunInstance cloudtrail json log


getting [ERROR] IndexError: list index out of range in lambda while trying to fetch InstanceId from RunInstance cloudtrail json log:

[ERROR] IndexError: list index out of range
Traceback (most recent call last):

any idea that how would I fetch the instaceid, and the tag from lambda_handler without any error ? any inputs


Solution

  • Check if there are any items before trying to access the first one. If no items are found, raise an exception.

    def getId(event):
        items = event.get('responseElements', {}).get('instancesSet', {}).get('items')
        if items:
            return items[0]['instanceId']
        raise ValueError('No items found')