Mastering AWS Lambda: Development, Configuration, and Integration
Develop code for AWS Lambda
Mastering AWS Lambda: Development, Configuration, and Integration
This hands-on lab guides you through the process of developing, configuring, and deploying an AWS Lambda function. You will learn to manage environment variables, tune performance, and integrate with other AWS services while following the AWS Certified Developer - Associate (DVA-C02) curriculum.
[!WARNING] Remember to run the teardown commands at the end of this lab to avoid ongoing charges to your AWS account.
Prerequisites
To successfully complete this lab, you need:
- An AWS Account with administrative access.
- AWS CLI installed and configured (
aws configure). - Python 3.9+ installed locally for code packaging.
- Basic familiarity with the Linux/macOS terminal or Windows PowerShell.
Learning Objectives
By the end of this lab, you will be able to:
- Create an IAM Execution Role with the principle of least privilege.
- Develop and deploy a Lambda function using the AWS CLI and Management Console.
- Configure environment variables and memory settings for optimal performance.
- Implement an event-driven integration using Amazon S3 as a trigger.
- Monitor execution logs and troubleshoot common runtime errors.
Architecture Overview
In this lab, we build a serverless image-processing metadata extractor. When a file is uploaded to S3, Lambda triggers, reads the metadata, and logs the results to CloudWatch.
Step-by-Step Instructions
Step 1: Create the IAM Execution Role
Lambda functions require an execution role to grant permissions to access other AWS services (like S3 and CloudWatch).
# 1. Create the Trust Policy file
echo '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}' > trust-policy.json
# 2. Create the IAM Role
aws iam create-role --role-name brainybee-lambda-role --assume-role-policy-document file://trust-policy.json
# 3. Attach the Basic Execution Policy (for Logging)
aws iam attach-role-policy --role-name brainybee-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole▶Console alternative
Navigate to
. Select
, choose
, and search for
AWSLambdaBasicExecutionRoleto attach. Name it
brainybee-lambda-role.
Step 2: Prepare the Lambda Function Code
Create a Python script named lambda_function.py that simulates processing an S3 event.
import os
import json
def lambda_handler(event, context):
# Accessing Environment Variables
log_level = os.environ.get('LOG_LEVEL', 'INFO')
print(f"Log Level: {log_level}")
print(f"Received event: {json.dumps(event)}")
# Business logic placeholder
return {
'statusCode': 200,
'body': json.dumps('Metadata processed successfully!')
}# Package the function
zip function.zip lambda_function.pyStep 3: Create and Configure the Lambda Function
Now, we deploy the ZIP file to AWS, specifying runtime, handler, and memory limits.
aws lambda create-function --function-name brainybee-processor-func \
--zip-file fileb://function.zip --handler lambda_function.lambda_handler --runtime python3.9 \
--role arn:aws:iam::<YOUR_ACCOUNT_ID>:role/brainybee-lambda-role \
--memory-size 128 --timeout 10[!TIP] Use
aws sts get-caller-identity --query Account --output textto quickly find your Account ID.
Step 4: Configure Environment Variables
Environment variables allow you to change function behavior without updating the code.
aws lambda update-function-configuration --function-name brainybee-processor-func \
--environment "Variables={LOG_LEVEL=DEBUG,APP_ENV=development}"▶Console alternative
Open your function in the
. Go to
and click
. Add key-value pairs for
LOG_LEVELand
APP_ENV.
Checkpoints
| Verification Task | Command / Action | Expected Result |
|---|---|---|
| Verify Role | aws iam get-role --role-name brainybee-lambda-role | JSON output with Role ARN |
| Invoke Function | aws lambda invoke --function-name brainybee-processor-func out.json | Status code 200 in terminal |
| Check Logs | View CloudWatch Logs /aws/lambda/brainybee-processor-func | Log entry showing "Log Level: DEBUG" |
Concept Review: Performance Tuning
Lambda performance is primarily controlled by the Memory setting. Increasing memory also increases the proportional CPU power and network bandwidth.
\begin{tikzpicture} \draw[->] (0,0) -- (6,0) node[right] {Memory (MB)}; \draw[->] (0,0) -- (0,4) node[above] {Execution Time (ms)}; \draw[thick, blue] (0.5,3.5) .. controls (1.5,1) and (4,0.5) .. (5.5,0.4); \node[blue] at (4,2) {Inverse Relationship}; \draw[dashed] (1,0) -- (1,2.5); \draw[dashed] (4,0) -- (4,0.6); \node at (1,-0.3) {\small 128MB}; \node at (4,-0.3) {\small 1024MB}; \end{tikzpicture}
Troubleshooting
| Error | Likely Cause | Fix |
|---|---|---|
An error occurred (AccessDeniedException) | IAM role lacks permissions or trust policy is wrong. | Check trust-policy.json and attached policies. |
Task timed out after 10.01 seconds | Logic is too slow or memory is too low. | Increase --timeout or --memory-size. |
ModuleNotFoundError | Handler path is incorrect or ZIP structure is wrong. | Ensure lambda_function.py is at the root of the ZIP. |
Clean-Up / Teardown
Run these commands to remove all resources created in this lab.
# 1. Delete the Lambda Function
aws lambda delete-function --function-name brainybee-processor-func
# 2. Detach IAM Policies
aws iam detach-role-policy --role-name brainybee-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# 3. Delete the IAM Role
aws iam delete-role --role-name brainybee-lambda-role
# 4. Remove local files
rm function.zip lambda_function.py trust-policy.json out.jsonStretch Challenge
Goal: Implement a Dead Letter Queue (DLQ).
- Create an Amazon SQS queue named
lambda-dlq. - Update the Lambda configuration to send failed asynchronous invocations to this SQS queue using the
--dead-letter-configparameter. - Modify your code to intentionally throw an exception and verify the message arrives in the queue.
Cost Estimate
- AWS Lambda: 1 Million free requests per month (Free Tier). This lab costs $0.00.
- CloudWatch Logs: $0.50/GB ingested. This lab (a few KB) costs $0.00.
- IAM/S3 Trigger: No additional cost for basic configuration.