Creating Lambda Functions
Deployment Methods
Overview
┌─────────────────────────────────────────────────────────────┐
│ DEPLOYMENT METHODS │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. AWS CONSOLE │
│ ───────────── │
│ Web interface, ideal for testing/learning │
│ ✅ Simple ❌ Not automatable │
│ │
│ 2. AWS CLI │
│ ──────── │
│ Command line, scriptable │
│ ✅ Automatable ⚠️ More complex │
│ │
│ 3. SAM (Serverless Application Model) │
│ ─────────────────────────────────── │
│ AWS framework for serverless │
│ ✅ IaC ✅ Local testing ✅ Best practice │
│ │
│ 4. CloudFormation / Terraform │
│ ────────────────────────────── │
│ Complete Infrastructure as Code │
│ ✅ Production ✅ Reproducible │
│ │
└─────────────────────────────────────────────────────────────┘
Creation via AWS CLI
Step 1: Create the IAM Role
# 1. Create the trust policy file
cat > trust-policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
# 2. Create the role
aws iam create-role \
--role-name lambda-basic-role \
--assume-role-policy-document file://trust-policy.json
# 3. Attach the basic policy (logs)
aws iam attach-role-policy \
--role-name lambda-basic-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Step 2: Create the Code
# lambda_function.py
import json
def lambda_handler(event, context):
"""
Simple Hello World function
"""
# Retrieve the name from the event
name = event.get('name', 'World')
# Create the message
message = f"Hello, {name}!"
# Log
print(f"Processing request for: {name}")
# Return the response
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({
'message': message,
'input': event
})
}
Step 3: Package and Deploy
# 1. Zip the code
zip function.zip lambda_function.py
# 2. Create the function
aws lambda create-function \
--function-name hello-world \
--runtime python3.11 \
--role arn:aws:iam::123456789012:role/lambda-basic-role \
--handler lambda_function.lambda_handler \
--zip-file fileb://function.zip \
--timeout 30 \
--memory-size 256
# 3. Test the function
aws lambda invoke \
--function-name hello-world \
--payload '{"name": "AWS"}' \
--cli-binary-format raw-in-base64-out \
response.json
# 4. View the response
cat response.json
Environment Variables
Configuration
# Add environment variables
aws lambda update-function-configuration \
--function-name hello-world \
--environment 'Variables={
DB_HOST=mydb.example.com,
DB_NAME=production,
LOG_LEVEL=INFO
}'
Usage in Code
import os
import json
def lambda_handler(event, context):
# Read environment variables
db_host = os.environ.get('DB_HOST', 'localhost')
db_name = os.environ.get('DB_NAME', 'default')
log_level = os.environ.get('LOG_LEVEL', 'DEBUG')
print(f"[{log_level}] Connecting to {db_host}/{db_name}")
return {
'statusCode': 200,
'body': json.dumps({
'db_host': db_host,
'db_name': db_name
})
}
API Gateway Trigger
Architecture
┌─────────────────────────────────────────────────────────────┐
│ API GATEWAY + LAMBDA │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Client │ │
│ │ │ │ │
│ │ │ GET /hello?name=AWS │ │
│ │ ▼ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ API Gateway │ │ │
│ │ │ │ │ │
│ │ │ • Authentication │ │
│ │ │ • Rate limiting │ │
│ │ │ • CORS │ │
│ │ └────────┬────────┘ │ │
│ │ │ │ │
│ │ │ Invoke │ │
│ │ ▼ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ Lambda │ │ │
│ │ │ hello-world │ │ │
│ │ └────────┬────────┘ │ │
│ │ │ │ │
│ │ │ Response │ │
│ │ ▼ │ │
│ │ {"message": "Hello, AWS!"} │ │
│ │ │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Create the API
# 1. Create the HTTP API (v2, simpler)
aws apigatewayv2 create-api \
--name hello-api \
--protocol-type HTTP \
--target arn:aws:lambda:us-east-1:123456789012:function:hello-world
# 2. Add permission for API Gateway
aws lambda add-permission \
--function-name hello-world \
--statement-id apigateway-invoke \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com
Code for API Gateway
import json
def lambda_handler(event, context):
"""
Handler for API Gateway HTTP API
"""
# Extract parameters
query_params = event.get('queryStringParameters', {}) or {}
name = query_params.get('name', 'World')
# Extract the path
path = event.get('rawPath', '/')
method = event.get('requestContext', {}).get('http', {}).get('method', 'GET')
print(f"{method} {path} - name={name}")
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' # CORS
},
'body': json.dumps({
'message': f'Hello, {name}!',
'path': path,
'method': method
})
}
S3 Trigger
Configuration
# Add permission for S3
aws lambda add-permission \
--function-name process-upload \
--statement-id s3-trigger \
--action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::my-bucket \
--source-account 123456789012
# Configure the trigger on the bucket
aws s3api put-bucket-notification-configuration \
--bucket my-bucket \
--notification-configuration '{
"LambdaFunctionConfigurations": [
{
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:process-upload",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{"Name": "suffix", "Value": ".jpg"}
]
}
}
}
]
}'
Code for S3
import json
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
"""
Process files uploaded to S3
"""
for record in event['Records']:
# Extract file info
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
size = record['s3']['object']['size']
print(f"New file: s3://{bucket}/{key} ({size} bytes)")
# Download the file
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read()
# Process the file (example: resize image)
# processed = process_image(content)
# Save the result
# s3.put_object(Bucket=bucket, Key=f"processed/{key}", Body=processed)
print(f"Processing completed for {key}")
return {
'statusCode': 200,
'body': json.dumps('Processing completed')
}
Dependencies (Layers)
Concept
┌─────────────────────────────────────────────────────────────┐
│ LAMBDA LAYERS │
├─────────────────────────────────────────────────────────────┤
│ │
│ Layers allow sharing code/dependencies │
│ between multiple functions │
│ │
│ WITHOUT Layers: │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ + numpy │ │ + numpy │ │ + numpy │ │
│ │ + pandas │ │ + pandas │ │ + requests │ │
│ │ (50 MB) │ │ (50 MB) │ │ (30 MB) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ WITH Layers: │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ (code only) │ │ (code only) │ │ (code only) │ │
│ │ (1 KB) │ │ (1 KB) │ │ (1 KB) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ │
│ ┌───────▼───────┐ │
│ │ Layer: libs │ │
│ │ numpy, pandas │ │
│ │ (50 MB) │ │
│ └───────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Create a Layer
# 1. Create the structure
mkdir -p python/lib/python3.11/site-packages
# 2. Install dependencies
pip install requests -t python/lib/python3.11/site-packages/
# 3. Zip
zip -r layer.zip python/
# 4. Publish the layer
aws lambda publish-layer-version \
--layer-name my-dependencies \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.11
# 5. Attach to a function
aws lambda update-function-configuration \
--function-name hello-world \
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
Best Practices
┌─────────────────────────────────────────────────────────────┐
│ LAMBDA BEST PRACTICES │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ DO │
│ ──────── │
│ • Keep functions small and focused │
│ • Use environment variables │
│ • Reuse connections (outside the handler) │
│ • Log with print() or logging │
│ • Handle errors properly │
│ • Set an appropriate timeout │
│ │
│ ❌ AVOID │
│ ───────── │
│ • Monolithic functions │
│ • Hardcoding configurations │
│ • Creating connections in the handler │
│ • Ignoring errors │
│ • Timeout too long (wasteful if error) │
│ │
│ OPTIMIZED CODE: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ import boto3 │ │
│ │ import os │ │
│ │ │ │
│ │ # Connections OUTSIDE the handler (reused) │ │
│ │ dynamodb = boto3.resource('dynamodb') │ │
│ │ table = dynamodb.Table(os.environ['TABLE_NAME']) │ │
│ │ │ │
│ │ def lambda_handler(event, context): │ │
│ │ # Lightweight handler, reused connection │ │
│ │ return table.get_item(Key={'id': event['id']}) │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Summary
| Step | Command |
|---|---|
| Create role | aws iam create-role |
| Create function | aws lambda create-function |
| Test | aws lambda invoke |
| Update | aws lambda update-function-code |
| Add trigger | aws lambda add-permission |
Next section: Lambda Lab