Create a Python Lambda Function in AWS in 5 minutes

Create a new Python file called app.py

Include a handler function that will be what our Lambda function returns


def handler(event, context):
    return "Greetings %s from %s!" % (event["name"], event["city"])

In this case our function will take a two values in the payload and return them.

Create the permissions for your function. This will require the AWS cli to be configured. If you install the aws cli and type aws configure and answer the questions, you'll be good. You can install the AWS CLI using pip install awscli.

Create the IAM role with policy attached that will allow function execution

aws iam create-role --role-name lambda-ex --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}'

Now, zip up your app.py

zip -r app.zip app.py

Now, create the function, replacing with your AWS Account ID. You can find it on the IAM role page. You can quickly retrieve your account ID by running

aws sts get-caller-identity
aws lambda create-function --function-name pyHello --runtime python3.7 --zip-file fileb://app.zip --handler app.handler --role arn:aws:iam::<AccountID>:role/lambda-ex

Now invoke the function, passing in your Payload

aws lambda invoke --function-name pyHello --payload '{"name":"AJ", "city":"Cincy"}' output

Cat the output file to validate the success

This is good, but if we're going to use this as an API, the return has to be JSON serializable. Let's modify our code a bit to return this message properly:

import json
def handler(event, context):
    msg = "Greetings %s from %s!" % (event["name"], event["city"])
    return { 
        'statusCode': 200,
        'body': json.dumps(msg),
        'headers': {
            'Content-Type': 'application/json'
        }
    }

To update the function, save the changes and recreate the zip file and run:

aws lambda update-function-code --function-name pyHello --zip-file fileb://app.zip

If I'm working frequently on a function, I put it all in one:

rm -rf app.zip ; zip app.zip app.py ; aws lambda update-function-code --function-name pyHello --zip-file fileb://app.zip

Rerun the test to confirm json output. cat output {"statusCode": 200, "body": "\"Greetings AJ from Cincy. !\"", "headers": {"Content-Type": "application/json"}}

Delete the function with the following command:

aws lambda delete-function --function-name pyHello

Thanks to this video for the guidance

I hope you find this helpful.

AJ

No Comments Yet