Mastering AWS Lambda with Boto3 and Python: Creating and Managing Lambda Functions with Boto3
Article outline:
- Introduction
- Creating a Simple Lambda Function
- Updating a Lambda Function
- Deleting a Lambda Function
- Conclusion and Next Steps
Introduction
Welcome back to the second installment in our series, “Mastering AWS Lambda with Boto3 and Python.” In this article, we will focus on creating, updating, and deleting AWS Lambda functions using the Boto3 library. We will take a deeper dive into specific parameters like Roles, Runtime, and Handler, among other topics.
Creating a Simple Lambda Function
To create a Lambda function using Boto3, you will need to initialize a Boto3 client for Lambda and then call the create_function
method. Here's a basic example:
import boto3
client = boto3.client('lambda')
response = client.create_function(
FunctionName='my_lambda_function',
Role='arn:aws:iam::account-id:role/execution_role',
Handler='my_handler.my_function',
Runtime='python3.8',
Code={
'ZipFile': b'fileb://my_function.zip'
}
)
Roles Parameter of create_function
The Role
parameter specifies the IAM role that AWS Lambda assumes when it executes your function. You can find this role in the AWS Console by navigating to IAM, then Roles. Look for a role that grants the necessary permissions for your Lambda function to access other AWS services.
Runtime Parameter of create_function
The Runtime
parameter specifies the programming language runtime. For Python, you can specify runtimes like python3.8
or python3.9
.
Handler Parameter of create_function
The Handler
parameter specifies the entry point of your Lambda function. It's a string in the format 'file_name.method'
, where file_name
is the name of the Python file and method
is the Python function to be invoked when the Lambda function is triggered.
Updating a Lambda Function
To update an existing Lambda function, you can use the update_function_code
or update_function_configuration
methods. For example:
response = client.update_function_code(
FunctionName='my_lambda_function',
ZipFile=b'fileb://my_updated_function.zip'
)
Deleting a Lambda Function
You can easily delete a Lambda function using the delete_function
method:
response = client.delete_function(
FunctionName='my_lambda_function'
)
How to Test a Lambda Function in the AWS Console
- Navigate to the AWS Lambda Console.
- Select the function you want to test.
- Click on the “Test” button at the top of the page.
- In the dialog that appears, you can either select one of the pre-configured test events or create a new one.
- Click “Save changes” and then “Test” to execute the function.
Step-by-Step HelloWorld Example
Step 1: Create a Python file named hello_world.py
and add the following code:
import os
def lambda_handler(event, context):
name = os.environ.get('NAME', 'World') # Retrieve the NAME environment variable
return {
'statusCode': 200,
'body': f'Hello, {name}!'
}
Here, we import the os
module to access environment variables. The function will return a greeting that uses the value of the NAME
environment variable, defaulting to 'World' if it's not set.
Step 2: Set Environment Variables
For demonstration purposes, we’ll set an environment variable directly in the code, but keep in mind that in a production scenario, you’d set this via the AWS Management Console or programmatically via Boto3 when creating or updating the Lambda function. You’ll see how to do this programmatically in Step 4.
Step 3: Package the Function into a ZIP File
- Save the
hello_world.py
file. - Create a ZIP file and add
hello_world.py
to it. Name the ZIP filehello_world.zip
.
You can create the ZIP file manually or use a command like zip -r hello_world.zip hello_world.py
from the terminal, depending on your operating system.
Step 4: Create the Lambda Function
Now let’s create the Lambda function using Boto3. The following Python code accomplishes this:
import boto3
client = boto3.client('lambda', region_name='us-east-1') # replace with your region
with open('hello_world.zip', 'rb') as f:
zip_file = f.read()
response = client.create_function(
FunctionName='HelloWorldLambda',
Role='arn:aws:iam::1234567890:role/LambdaHelloWorldRole', # Replace with your IAM role ARN
Handler='hello_world.lambda_handler',
Runtime='python3.8',
Code={'ZipFile': zip_file},
Environment={
'Variables': {
'NAME': 'John' # Setting the NAME environment variable
}
}
)
If you dont know how to create a role here is step-by-step guide.
This code snippet reads the ZIP file into a byte array and uses it in the create_function
call. Replace the Role
parameter with the ARN of your IAM role.
Step 5: Run the Lambda Function
Now that we’ve created the Lambda function, we can invoke it using Boto3 as follows:
response = client.invoke(
FunctionName='HelloWorldLambda',
InvocationType='RequestResponse'
)
payload = response['Payload'].read().decode('utf-8')
print(f"Lambda response: {payload}")
Alternatively, you can go to the AWS Management Console:
- Navigate to the Lambda service.
- Select your function (
HelloWorldLambda
in this case). - Click the “Test” button.
- Configure a new test event or use an existing one, then click “Save changes.”
- Finally, click the “Test” button again to execute the function.
By following these steps, you’ll create a simple HelloWorld Lambda function, package it into a ZIP file, and run it either programmatically using Boto3 or manually via the AWS Management Console.