Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计异常

aws-lambdaAWS lambda 部署

Agent Skill

用于辅助云资源、部署、容器、基础设施和运维自动化任务。它适合让 Agent 检查配置、整理部署步骤、分析资源状态、生成排障思路或辅助云服务接入。使用时需要明确目标环境、账号权限、区域和资源组,区分本地测试与生产操作;涉及删除资源、重启服务、修改网络或权限配置时,应先确认影响范围。

总安装

792

周安装

33

GitHub Stars

18

下载量

264
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:aws-lambda(AWS lambda 部署)
来源仓库:https://github.com/bagelhole/devops-security-agent-skills
仓库路径:skills/aws-lambda
安装命令:
npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill aws-lambda
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill aws-lambda

简介

用于辅助构建和部署 AWS Lambda 无服务器应用,涵盖函数创建、事件源配置及冷启动优化。

  • 适合开发 API 网关触发器、定时任务或数据流处理等事件驱动型服务。
  • 通过 CLI 或 SAM 模板管理函数、层(Layer)和资源编排,支持 Python 与 Node.js。
  • 需提前安装 AWS CLI v2 并配置 IAM 权限,区分开发与生产环境操作。
  • 涉及删除或修改资源时,应评估影响范围并确认权限策略。

SKILL.md

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
  • IAM permissions: lambda:*, iam:PassRole, logs:*, apigateway:*, s3:*
  • 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 handler with structured logging
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", "{}"))
        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 here

Lambda 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.12

Event 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)

# Create a function URL (public HTTPS endpoint)
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

Cold Start Optimization

# Enable provisioned concurrency to eliminate cold starts
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-handler

Cold start reduction tips:

  • Use arm64 architecture (Graviton) for faster init and lower cost
  • 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.yaml - AWS SAM application
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My serverless API

Globals:
  Function:
    Runtime: python3.12
    Architectures: [arm64]
    MemorySize: 256
    Timeout: 30
    Tracing: Active
    Environment:
      Variables:
        STAGE: !Ref Stage
        LOG_LEVEL: INFO

Parameters:
  Stage:
    Type: String
    Default: dev
    AllowedValues: [dev, staging, prod]

Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub "${Stage}-api-handler"
      Handler: app.handler
      CodeUri: src/
      Layers:
        - !Ref DepsLayer
      Events:
        GetItems:
          Type: Api
          Properties:
            Path: /items
            Method: get
        PostItem:
          Type: Api
          Properties:
            Path: /items
            Method: post
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref ItemsTable

  QueueProcessor:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub "${Stage}-queue-processor"
      Handler: sqs_processor.handler
      CodeUri: src/
      Events:
        SQSEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt ProcessingQueue.Arn
            BatchSize: 10
            FunctionResponseTypes:
              - ReportBatchItemFailures

  DepsLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: common-deps
      ContentUri: layer/
      CompatibleRuntimes:
        - python3.12

  ItemsTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub "${Stage}-items"
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH

  ProcessingQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "${Stage}-processing"
      VisibilityTimeout: 360

Outputs:
  ApiEndpoint:
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod"
# SAM CLI commands
sam build
sam local invoke ApiFunction --event events/get-items.json
sam local start-api --port 3000
sam deploy --guided
sam logs --name ApiFunction --stack-name my-stack --tail

Troubleshooting

ProblemCauseFix
Function times outTimeout too low or downstream slowIncrease timeout; check VPC/NAT config
Out of memoryMemory limit too smallIncrease --memory-size; profile with CloudWatch Insights
Permission denied on AWS APIExecution role missing policyAttach required policy to the execution role
Cold starts > 5sLarge package or VPC overheadUse layers, arm64, provisioned concurrency; remove VPC if not needed
SQS messages reprocessedVisibility timeout < function timeoutSet queue visibility timeout to 6x function timeout
Event source mapping disabledToo many consecutive errorsFix the function error; re-enable the mapping
Layer not foundWrong region or deleted versionVerify layer ARN region matches function region
Canary deployment not shiftingAlias routing config wrongVerify version numbers in routing config
Cannot invoke function URLMissing resource-based policyAdd lambda:InvokeFunctionUrl permission

Related Skills

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.58%
按下载量换算94

Claude

32.79%
按下载量换算87

Cursor

17.61%
按下载量换算46

Gemini CLI

10.24%
按下载量换算27

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

未通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills