Lambda Fundamentals
- Event-driven execution: Does not run without a trigger (no idle cost)
- Maximum execution time: 15 minutes
- Memory: 128MB ~ 10GB (CPU scales with memory)
- Billing: Number of requests + execution duration (ms)
- Cold start: Container initialization time on first invocation
Your First Lambda Function (Python)
Python
# lambda_function.py
import json
def lambda_handler(event, context):
"""Lambda handler — entry point for every function"""
print(f"Event: {json.dumps(event)}")
name = event.get('name', 'World')
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': f'Hello, {name}!'})
}Creating a Function with the CLI
Bash
# Create an IAM role (Lambda execution permissions)
aws iam create-role --role-name lambda-basic-role --assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'
# Attach the basic execution policy
aws iam attach-role-policy --role-name lambda-basic-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# Zip the code
zip function.zip lambda_function.py
# Create the function
aws lambda create-function --function-name my-function --runtime python3.12 --role arn:aws:iam::ACCOUNT_ID:role/lambda-basic-role --handler lambda_function.lambda_handler --zip-file fileb://function.zip --timeout 30 --memory-size 256
# Invoke a test
aws lambda invoke --function-name my-function --payload '{"name": "Alice"}' response.json
cat response.json
# Update the code
zip function.zip lambda_function.py
aws lambda update-function-code --function-name my-function --zip-file fileb://function.zipConfiguring Environment Variables
Bash
aws lambda update-function-configuration --function-name my-function --environment 'Variables={DB_HOST=localhost,DB_NAME=mydb,ENV=production}'
# Use inside the function
import os
db_host = os.environ['DB_HOST']API Gateway Trigger (HTTP Endpoint)
Bash
# Create an HTTP API (v2, simpler and cheaper)
aws apigatewayv2 create-api --name my-api --protocol-type HTTP --target arn:aws:lambda:ap-northeast-2:ACCOUNT:function:my-function
# Grant API Gateway permission to invoke Lambda
aws lambda add-permission --function-name my-function --statement-id api-gateway-invoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com
# Get the API endpoint
aws apigatewayv2 get-apis --query 'Items[0].ApiEndpoint'Scheduled Execution with EventBridge (cron)
Bash
# Create a rule (every day at 09:00 UTC)
aws events put-rule --name daily-job --schedule-expression "cron(0 9 * * ? *)" --state ENABLED
# Set Lambda as the target
aws events put-targets --rule daily-job --targets '[{
"Id": "lambda-target",
"Arn": "arn:aws:lambda:ap-northeast-2:ACCOUNT:function:my-function"
}]'
# Grant EventBridge permission to invoke Lambda
aws lambda add-permission --function-name my-function --statement-id eventbridge-invoke --action lambda:InvokeFunction --principal events.amazonaws.com --source-arn arn:aws:events:ap-northeast-2:ACCOUNT:rule/daily-jobS3 Event Trigger (Process on File Upload)
Bash
# Configure S3 bucket notifications
aws s3api put-bucket-notification-configuration --bucket my-bucket --notification-configuration '{
"LambdaFunctionConfigurations": [{
"LambdaFunctionArn": "arn:aws:lambda:ap-northeast-2:ACCOUNT:function:my-function",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {"FilterRules": [{"Name": "suffix", "Value": ".jpg"}]}
}
}]
}'Viewing Logs
Bash
# Tail recent logs
aws logs tail /aws/lambda/my-function --follow
# Specific time range
aws logs filter-log-events --log-group-name /aws/lambda/my-function --start-time $(date -d '1 hour ago' +%s000)Editorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)AWS documentation ↗Python documentation ↗
Questions & answers
Ask a question about this guide. We'll review and reply.