aws-lambda – skill DevOps & Hạ tầng cho agent AI
Xây dựng và triển khai hàm serverless trên AWS Lambda. Cấu hình trigger, quản lý quyền và tối ưu hiệu năng. Dùng khi triển khai ứng dụng serverless.
Cài skill aws-lambda bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/aws-lambda-f81aa.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /aws-lambda – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/aws-lambda-f81aa.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $aws-lambda – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/aws-lambda-f81aa.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /aws-lambda – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/aws-lambda-f81aa.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /aws-lambda – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
AWS Lambda
Build serverless applications with AWS Lambda, covering function creation, event sources, layers, SAM templates, and cold start optimization.
When to Use This Skill
- Building event-driven applications triggered by API Gateway, S3, SQS, or EventBridge
- Running scheduled tasks (cron) without managing servers
- Processing data streams from Kinesis or DynamoDB
- Building lightweight APIs with API Gateway or function URLs
- Implementing webhooks, Slack bots, or automation scripts
- Reducing compute costs for intermittent or bursty workloads
Prerequisites
- AWS CLI v2 installed and configured
- Least-privilege IAM actions for the chosen resources; restrict
iam:PassRoleto the execution role. Wildcard service grants are not a prerequisite. - Python 3.11+, Node.js 20+, or another supported runtime installed locally
- (Optional) AWS SAM CLI for local development and deployment
Create and Deploy a Function
# Create a deployment package
cd my-function
zip -r function.zip app.py
# Create the Lambda function
aws lambda create-function \
--function-name my-api-handler \
--runtime python3.12 \
--handler app.handler \
--role arn:aws:iam::123456789012:role/LambdaExecRole \
--zip-file fileb://function.zip \
--memory-size 256 \
--timeout 30 \
--environment 'Variables={STAGE=production,LOG_LEVEL=INFO}' \
--architectures arm64 \
--tracing-config Mode=Active \
--tags '{"Team":"backend","Environment":"production"}'
# Update function code
aws lambda update-function-code \
--function-name my-api-handler \
--zip-file fileb://function.zip
# Update function configuration
aws lambda update-function-configuration \
--function-name my-api-handler \
--memory-size 512 \
--timeout 60 \
--environment 'Variables={STAGE=production,LOG_LEVEL=WARNING}'
# Publish a version (immutable snapshot)
aws lambda publish-version \
--function-name my-api-handler \
--description "v1.2.0 - added rate limiting"
# Create an alias pointing to the version
aws lambda create-alias \
--function-name my-api-handler \
--name live \
--function-version 3
# Weighted alias for canary deployments (90% v3, 10% v4)
aws lambda update-alias \
--function-name my-api-handler \
--name live \
--function-version 4 \
--routing-config '{"AdditionalVersionWeights":{"3":0.9}}'Function Code Examples
# app.py - API Gateway REST proxy (v1) sketch; not the function URL/v2 event shape
import json
import logging
import os
logger = logging.getLogger()
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
def handler(event, context):
"""Handle API Gateway proxy event."""
logger.info("Request: %s %s", event["httpMethod"], event["path"])
try:
body = json.loads(event.get("body") or "{}")
result = process_request(body)
return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"X-Request-Id": context.aws_request_id
},
"body": json.dumps(result)
}
except ValueError as e:
logger.warning("Validation error: %s", e)
return {"statusCode": 400, "body": json.dumps({"error": str(e)})}
except Exception as e:
logger.exception("Unhandled error")
return {"statusCode": 500, "body": json.dumps({"error": "Internal server error"})}
def process_request(body):
return {"message": "OK", "data": body}# sqs_processor.py - SQS batch processor with partial failure reporting
import json
import logging
logger = logging.getLogger()
logger.setLevel("INFO")
def handler(event, context):
"""Process SQS messages with partial batch failure reporting."""
failed_ids = []
for record in event["Records"]:
try:
body = json.loads(record["body"])
logger.info("Processing message: %s", record["messageId"])
process_message(body)
except Exception as e:
logger.error("Failed message %s: %s", record["messageId"], e)
failed_ids.append(record["messageId"])
# Return failed items so only those get retried
return {
"batchItemFailures": [
{"itemIdentifier": msg_id} for msg_id in failed_ids
]
}
def process_message(body):
pass # your logic hereLambda Layers
# Build a layer for Python dependencies
mkdir -p layer/python
pip install requests boto3-stubs -t layer/python/
cd layer
zip -r ../my-layer.zip python/
# Publish the layer
aws lambda publish-layer-version \
--layer-name common-deps \
--description "Shared Python dependencies" \
--zip-file fileb://my-layer.zip \
--compatible-runtimes python3.11 python3.12 \
--compatible-architectures arm64 x86_64
# Attach layer to a function
aws lambda update-function-configuration \
--function-name my-api-handler \
--layers "arn:aws:lambda:us-east-1:123456789012:layer:common-deps:1"
# List available layers
aws lambda list-layers --compatible-runtime python3.12Event Source Mappings
# SQS trigger with batch processing
aws lambda create-event-source-mapping \
--function-name sqs-processor \
--event-source-arn arn:aws:sqs:us-east-1:123456789012:my-queue \
--batch-size 10 \
--maximum-batching-window-in-seconds 5 \
--function-response-types ReportBatchItemFailures
# DynamoDB Streams trigger
aws lambda create-event-source-mapping \
--function-name stream-processor \
--event-source-arn arn:aws:dynamodb:us-east-1:123456789012:table/my-table/stream/2026-01-01T00:00:00.000 \
--batch-size 100 \
--starting-position LATEST \
--maximum-retry-attempts 3 \
--bisect-batch-on-function-error \
--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:123456789012:dlq"}}'
# S3 event notification (via Lambda permission + S3 config)
aws lambda add-permission \
--function-name image-processor \
--statement-id s3-trigger \
--action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::my-uploads-bucket \
--source-account 123456789012
aws s3api put-bucket-notification-configuration \
--bucket my-uploads-bucket \
--notification-configuration '{
"LambdaFunctionConfigurations": [{
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:image-processor",
"Events": ["s3:ObjectCreated:*"],
"Filter": {"Key": {"FilterRules": [{"Name": "suffix", "Value": ".jpg"}]}}
}]
}'
# Schedule with EventBridge (cron)
aws events put-rule \
--name daily-cleanup \
--schedule-expression "cron(0 2 * * ? *)" \
--state ENABLED
aws lambda add-permission \
--function-name daily-cleanup \
--statement-id eventbridge \
--action lambda:InvokeFunction \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-east-1:123456789012:rule/daily-cleanup
aws events put-targets \
--rule daily-cleanup \
--targets '[{"Id":"1","Arn":"arn:aws:lambda:us-east-1:123456789012:function:daily-cleanup"}]'Function URLs (No API Gateway Needed)
# Public access requires explicit authorization; CORS is not authentication.
# Prefer AWS_IAM for private endpoints. Create public URL only when requested.
aws lambda create-function-url-config \
--function-name my-api-handler \
--auth-type NONE \
--cors '{
"AllowOrigins": ["https://myapp.com"],
"AllowMethods": ["GET", "POST"],
"AllowHeaders": ["Content-Type"],
"MaxAge": 86400
}'
# Grant public invoke for function URL
aws lambda add-permission \
--function-name my-api-handler \
--statement-id function-url-public \
--action lambda:InvokeFunctionUrl \
--principal "*" \
--function-url-auth-type NONE
aws lambda add-permission \
--function-name my-api-handler \
--statement-id function-url-public-invoke \
--action lambda:InvokeFunction \
--principal "*" \
--invoked-via-function-urlCold Start Optimization
# Provision capacity to reduce cold starts within provisioned concurrency; spillover may initialize
aws lambda put-provisioned-concurrency-config \
--function-name my-api-handler \
--qualifier live \
--provisioned-concurrent-executions 10
# Set reserved concurrency (throttle limit)
aws lambda put-function-concurrency \
--function-name my-api-handler \
--reserved-concurrent-executions 100
# Enable SnapStart for Java functions (near-zero cold starts)
aws lambda update-function-configuration \
--function-name my-java-handler \
--snap-start '{"ApplyOn": "PublishedVersions"}'
aws lambda publish-version --function-name my-java-handlerCold start reduction tips:
- Benchmark supported architectures; verify native dependency compatibility and regional pricing
- Minimize deployment package size; use layers for large dependencies
- Initialize SDK clients outside the handler function
- Avoid VPC unless required (VPC cold starts are longer)
- Use provisioned concurrency for latency-sensitive paths
SAM Template
# template.y… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- aws-penetration-testing – Cung cấp kỹ thuật kiểm thử xâm nhập môi trường đám mây AWS toàn diện. Bao gồm liệt kê…
- aws-rds – Cung cấp và quản lý cơ sở dữ liệu RDS. Cấu hình sao lưu, sao chép và bảo mật. Dùng khi…
- aws-s3 – Cấu hình S3 bucket, chính sách và quy tắc vòng đời. Triển khai versioning, replication…
- aws-secrets-manager – Lưu trữ và xoay vòng secret trong AWS Secrets Manager.
- helm-chart-scaffolding – Thiết kế, tổ chức và quản lý Helm chart để tạo template và đóng gói ứng dụng Kubernetes…
- aws-secrets-rotation – Tự động hóa việc xoay vòng secret AWS cho RDS, API key và thông tin xác thực
- aws-serverless – Skill chuyên biệt để xây dựng ứng dụng serverless sản xuất trên AWS. Bao gồm hàm Lambda…
- aws-serverless-eda – Chuyên gia kiến trúc serverless và hướng sự kiện trên AWS theo Well-Architected…