How to package and deploy a python lambda function using AWS CLI

In this article, we will take a look at the steps required to package a python lambda function and deploy it using AWS CLI.

Code the lambda function

For this example, let’s create a new directory named “hello-world-lambda” and create a file named “lambda_function.py” inside it.

Copy and paste the below code into the “lambda_function.py” file. This code defines a lambda handler function that simply prints the text “Hello World”.

def lambda_handler(event, context) {
	print("Hello World")
}

Package the lambda

Since this lambda doesn’t have any runtime dependencies i.e., it doesn’t need any additional libraries at runtime to execute, the lambda package will be a zip file that just contains the lambda_function.py file.

We can use any zip utility like 7zip or the compression facility provided by the OS to zip the file and create the package.

In the command prompt, execute the below commands

> cd hello-world-lambda
> zip hello-world-lambda-package.zip lambda_function.py

Deploy the lambda package

If the lambda function is already created and available in AWS, then we only need to update that function with the latest code present in the package that we just created.

aws lambda update-function-code \
--function-name hello-world-lambda \
--zip-file fileb://hello-world-lambda-package.zip

Alternatively, we can also navigate to the Lambda service in AWS console, open the function we are trying to update, and then use the upload button to upload the zip file and deploy the new package.

Create the Lambda Function

If the lambda function is not yet created in AWS, then we need to create it while deploying the package for the first time. One pre-requisite to creating a lambda function is to create a lambda execution role as that needs to be passed in the create-function API call.

For this example, let’s assume, we already have a lambda execution role created in IAM and have the ARN of that role.

Execute the below command to create a new lambda function and deploy the package that we just created.

aws lambda create-function \
--function-name hello-world-lambda-function \
--runtime python3.9 \
--zip-file fileb://hello-world-lambda-package.zip \
--role arn:aws:iam::1234567890:role/lambda-basic-role \
--handler lambda_function.lambda_handler

References

Leave a Comment

Your email address will not be published. Required fields are marked *