guitarhero23
guitarhero23

Reputation: 1145

AWS Lambda Handle Error in Python Without Lambda Retrying

By default if your Lambda function errors it will automatically retry another 2 times. I'm handling certain errors in a Lambda function that aren't really errors, it's basically if the json I'm searching for isn't in the returned json I log that it wasn't found and I would like the script to stop at that point as their isn't anything left for it to do. However as I'm doing try catch exceptions it's logging and exiting correctly but because it reports it as an error Lambda runs it again.

Is it my usage of sys.exit() that is causing it? I don't try/catch errors in the first example but it does retry.

Example: Loop through json nodes, if it finds a match than assign a variable, if it doesn't handle the exception and write to cloudwatch (print) that it didn't find a match.

while index < result_nodes:
        if TL2['message_response']['computers'][index]['resource_name'] == instance_name:
            resource_id = TL2['message_response']['computers'][index]['resource_id']
            index += 1

        index += 1
    if resource_id == '':
        print('No match found, quitting.')
        sys.exit()

Another similar usage

instance_name = ''
    try:
        for tag in response['Reservations'][0]['Instances'][0]['Tags']:
            if tag['Key'] == 'Name':
                instance_name = tag['Value']
        if instance_name == '':
            print('EC2 Instance name not set, quitting')
            sys.exit()
        else:
            print('Step 2 - Get Computer Name: ' + instance_name)
    except Exception:
        print('No tags exist for this terminated EC2 instance, quitting.')
        sys.exit()

Upvotes: 2

Views: 2020

Answers (1)

jimmone
jimmone

Reputation: 466

Try removing the sys.exit() and it shouldn't retry anymore. Similar situation https://stackoverflow.com/a/52739848/12103989

Upvotes: 4

Related Questions