Guide for creating, deploying, and managing AWS Lambda serverless functions with handlers, triggers, and CloudWatch integration.
This skill guides you through creating, deploying, and managing AWS Lambda serverless functions based on AWS documentation best practices.
Helps you build AWS Lambda functions from scratch, covering:
Before creating Lambda functions:
When creating a new Lambda function:
**For Node.js (ESM):**
```javascript
export const handler = async (event, context) => {
// Extract parameters from event object
const param1 = event.param1;
const param2 = event.param2;
// Business logic
const result = processData(param1, param2);
// Logging for CloudWatch
console.log(`Processed result: ${result}`);
console.log('CloudWatch log group:', context.logGroupName);
// Return JSON response
return JSON.stringify({
statusCode: 200,
body: result
});
};
function processData(param1, param2) {
// Your logic here
return param1 + param2;
}
```
**For Python:**
```python
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
# Extract parameters from event dictionary
param1 = event['param1']
param2 = event['param2']
# Business logic
result = process_data(param1, param2)
# Logging for CloudWatch
print(f"Processed result: {result}")
logger.info(f"CloudWatch log group: {context.log_group_name}")
# Return JSON response
return json.dumps({
'statusCode': 200,
'body': result
})
def process_data(param1, param2):
# Your logic here
return param1 + param2
```
Set up essential Lambda configuration:
- Minimum: `AWSLambdaBasicExecutionRole` for CloudWatch Logs
- Add additional policies for AWS service integrations (S3, DynamoDB, etc.)
**Event Object:**
**Context Object:**
- `context.logGroupName` / `context.log_group_name`: CloudWatch Logs group
- `context.requestId` / `context.aws_request_id`: Unique invocation ID
- `context.functionName` / `context.function_name`: Function name
- `context.getRemainingTimeInMillis()` / `context.get_remaining_time_in_millis()`: Time left before timeout
**For Node.js:**
```javascript
console.log(JSON.stringify({
level: 'INFO',
message: 'Processing started',
requestId: context.requestId,
data: { userId: event.userId }
}));
```
**For Python:**
```python
logger.info('Processing started', extra={
'requestId': context.aws_request_id,
'userId': event['userId']
})
```
Create and run test events:
1. Navigate to "Test" tab in Lambda console
2. Create new test event with JSON payload matching your function's expected input
3. Example test event:
```json
{
"param1": 10,
"param2": 5
}
```
4. Click "Test" to invoke function
5. Review execution results, logs, and duration
6. Check CloudWatch Logs for detailed log output (link provided in test results)
**Via Console:**
**Via CLI/SDK (for compiled languages or CI/CD):**
```bash
zip function.zip index.js
aws lambda update-function-code \
--function-name myLambdaFunction \
--zip-file fileb://function.zip
```
Access function metrics and logs:
When deleting a function:
1. Navigate to Lambda console
2. Select function to delete
3. Choose "Actions" → "Delete function"
4. Confirm deletion
5. Manually delete associated resources:
- CloudWatch Log groups (if not auto-deleted)
- IAM execution roles (if custom-created)
- EventBridge rules or other triggers
**Example 1: Simple Data Processing Function**
```javascript
// Calculate area from dimensions
export const handler = async (event) => {
const { length, width } = event;
const area = length * width;
return {
statusCode: 200,
body: JSON.stringify({ area })
};
};
```
**Example 2: S3 Event Handler**
```python
def lambda_handler(event, context):
# Process S3 upload event
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
logger.info(f"Processing {key} from {bucket}")
# Your S3 processing logic here
return {'statusCode': 200}
```
**Example 3: API Gateway Integration**
```javascript
export const handler = async (event) => {
// Parse API Gateway request
const body = JSON.parse(event.body);
const userId = event.pathParameters.userId;
// Process request
const result = await processUserData(userId, body);
// Return API Gateway-compatible response
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(result)
};
};
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/aws-lambda-function-development/raw