Working with AWS Lambda in Python using Boto3

Tuvshinsanaa Tuul

Tuvshinsanaa Tuul

AWS Lambda is a serverless compute highly scalable and cost-efficient service provided by Amazon Web Services (AWS) that allows you to execute code in the form of self-contained applications in an efficient and flexible manner. It can perform any kind of computing task, from serving web pages and processing streams of data to calling APIs and integrating with other AWS and non-AWS services. This article covers how to work with AWS Lambda service using Python SDK for AWS (Boto3 library) to deploy Lambda functions, update them, and manage permissions for other services to invoke Lambda function.

How to create Lamda function using Boto3

To create a Lambda function using Boto3, you need to use the create_function() method of the Lambda Boto3 client. In addition to that, you need to zip your Lambda function code and create a Lambda execution IAM role.

Following is the code for creating an IAM role which then later will be used to execute a Lambda function.

import boto3
import json

iam = boto3.client('iam')

role_policy = {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}


response = iam.create_role(
  RoleName='LambdaBasicExecution',
  AssumeRolePolicyDocument=json.dumps(role_policy),
)

print(response)
Create Lambda execution role
Create Lambda execution role

Here’s an example of a simple Lambda function that returns “Hello World”.

Lambda functions need an entry point handler that accepts the arguments event and context.

import json

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps('Hello World')
    }
Zip Python Code
Zip Python Code

The following code will create a new AWS Lambda function called helloWorldLambda.

Note: the Handler parameter is specifying the entry point for the Lambda function will be a function called lambda_handler in the handler.py file.

import boto3

iam_client = boto3.client('iam')
lambda_client = boto3.client('lambda')

with open('lambda.zip', 'rb') as f:
	zipped_code = f.read()
  
role = iam_client.get_role(RoleName='LambdaBasicExecution')

response = lambda_client.create_function(
    FunctionName='helloWorldLambda',
    Runtime='python3.9',
    Role=role['Role']['Arn'],
    Handler='handler.lambda_handler',
    Code=dict(ZipFile=zipped_code),
    Timeout=300, # Maximum allowable timeout
)

print(response)
Create Lambda function
Create Lambda function using Boto3

To create a Lambda function zip archive from Python code, you need to use the shutil.make_archive() method.

import shutil
shutil.make_archive(output_filename, 'zip', dir_name)

As a result of the above code execution, you should see a new Lambda function in the AWS web console:

helloWorldLambda function
helloWorldLambda function

How to invoke Lambda function using Boto3

To invoke the Lambda function, you need to use the invoke() function of the Boto3 client. To send input to your Lambda function, you need to use the Payload argument, which should contain JSON string data. Data provided to the Payload argument is available in the Lambda function as an event argument of the Lambda handler function.

import boto3, json

lambda_client = boto3.client('lambda')

test_event = dict()

response = lambda_client.invoke(
  FunctionName='helloWorldLambda',
  Payload=json.dumps(test_event),
)

print(response['Payload'])
print(response['Payload'].read().decode("utf-8"))
Invoke Lambda function
Invoke Lambda function

Lambda function version

You can use versions to manage the deployment of your functions. For example, you can publish a new version of a function for beta testing without affecting users of the stable production version. Lambda creates a new version of your function each time that you publish the function. The new version is a copy of the unpublished version of the function.

Create Lambda function version

To create/publish a new Lambda function version, you need to use the publish_version() method of the Lambda client.

You can change the function code and settings only on the unpublished version of a function. When you publish a version, the code and settings are locked to maintain a consistent experience for users of that version.

The publish_version() function publishes a version of your function from the current snapshot of $LATEST.

import boto3

lambda_client = boto3.client('lambda')

response = lambda_client.publish_version(
    FunctionName='helloWorldLambda',
)

print(response)
Publish new Lambda version
Publish new Lambda version

Lambda function alias

You can create one or more aliases for your Lambda function. A Lambda alias is like a pointer to a specific function version. Users can access the function version using the alias Amazon Resource Name (ARN). Alias names are unique for a given function.

Each Lambda function alias has a unique ARN. An alias can point only to a function version, not to another alias. You can update an alias to point it to a new version of the function.

Event sources such as Amazon Simple Storage Service (Amazon S3) invoke your Lambda function. These event sources maintain a mapping that identifies the function to invoke when events occur. If you specify a Lambda function alias in the mapping configuration, you don’t need to update the mapping when the function version changes.

Create Lambda function alias

To create a Lambda function alias, you need to use the create_alias() method of the Lambda client.

To create an alias for the Lambda function, you need to publish a new version for Lambda first.

import boto3

lambda_client = boto3.client('lambda')

response = lambda_client.create_alias(
    FunctionName='helloWorldLambda',
    Name='v1',
    FunctionVersion='1',
    Description='helloWorldLambda v1',
)

print(response)
Create Lambda function alias
Create Lambda function alias

List Lambda function aliases

To list Lambda function aliases, you need to use the list_aliases() method of the Lambda client. For each alias, the response includes information such as the alias ARN, description, alias name, and the function version to which it points.

You can optionally use parameter FunctionVersion to filter out the result.

import boto3

lambda_client = boto3.client('lambda')

response = lambda_client.list_aliases(
    FunctionName='helloWorldLambda',
    FunctionVersion='1',
)

aliases = response['Aliases']

print([alias for alias in aliases])
List Lambda function aliases
List Lambda function aliases

Describe Lambda function

To describe the Lambda function, you need to use the get_function() method of the Lambda client. Response data will contain the configuration information of the Lambda function and a presigned URL link to the .zip file with the source code of your function.

Note: the URL is valid for 10 minutes. The configuration information is the same information you’ve provided as parameters when uploading the function.

import boto3

lambda_client = boto3.client('lambda')

response = lambda_client.get_function(
    FunctionName='helloWorldLambda'
)

print(response)
Describe Lambda function
Describe Lambda function

Update Lambda function

To update the Lambda function, you need to use the update_function_code() method of the Lambda client.

import boto3

lambda_client = boto3.client('lambda')

with open('lambda.zip', 'rb') as f:
    zipped_code = f.read()

response = lambda_client.update_function_code(
    FunctionName='helloWorldLambda',
    ZipFile=zipped_code
)

print(response)

To create a Lambda function zip archive from Python code, you need to use the shutil.make_archive() method.

import shutil
shutil.make_archive(output_filename, 'zip', dir_name)
Update Lambda code
Update Lambda code

Grant InvokeLambda permission to AWS services

To grant permission to the AWS service to invoke the Lambda function, you need to use the add_permission() method of the Lambda client.

Permissions apply to the Amazon Resource Name (ARN) used to invoke the function, which can be unqualified (the unpublished version of the function), or includes a version or alias. If a client uses a version or alias to invoke a function, use the Qualifier parameter to apply permissions to that ARN.

This action adds a statement to a resource-based permissions policy for the function.

The following code will add permission for test-ap-s3-bucket S3 bucket to invoke helloWorldLambda Lamda function.

import boto3

lambda_client = boto3.client('lambda') 

response = lambda_client.add_permission(
    StatementId='S3InvokeHelloWorldLambda',
    FunctionName='helloWorldLambda',
    Action='lambda:InvokeLambda',
    Principal='s3.amazonaws.com',
    SourceArn='arn:aws:s3:::test-ap-s3-bucket/*',
)

print(response)
Add InvokeLambda permission to the S3 bucket
Add InvokeLambda permission to the S3 bucket
S3 Trigger added to the Lambda function
S3 Trigger added to the Lambda function

Delete Lambda function

To delete the Lambda function, you need to use the delete_function() method of the Lambda client.

import boto3

lambda_client = boto3.client('lambda')

response = lambda_client.delete_function(
    FunctionName='helloWorldLambda'
)

print(response)
Delete Lambda function
Delete Lambda function

Summary

In this article, we’ve covered how to manage AWS Lambda service using Python SDK for AWS (Boto3 library) to deploy, update and delete Lambda functions.

Related articles

How useful was this post?

Click on a star to rate it!

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Related Udemy Courses

Subscribe to our updates

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Want to be an author of another post?

We’re looking for skilled technical authors for our blog!

Leave a comment

If you’d like to ask a question about the code or piece of configuration, feel free to use https://codeshare.io/ or a similar tool as Facebook comments are breaking code formatting.