Skip to main content
ClaudeWave
Skill1.1k repo starsupdated 4d ago

lambda

AWS Lambda is a serverless compute service that executes code in response to events without requiring server provisioning. Use this skill when creating or updating Lambda functions, configuring event triggers from services like S3 or EventBridge, managing function layers and dependencies, debugging invocations, or optimizing performance through cold start mitigation and execution environment tuning.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/itsmostafa/aws-agent-skills /tmp/lambda && cp -r /tmp/lambda/skills/lambda ~/.claude/skills/lambda
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# AWS Lambda

AWS Lambda runs code without provisioning servers. You pay only for compute time consumed. Lambda automatically scales from a few requests per day to thousands per second.

## Table of Contents

- [Core Concepts](#core-concepts)
- [Common Patterns](#common-patterns)
- [CLI Reference](#cli-reference)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
- [References](#references)

## Core Concepts

### Function

Your code packaged with configuration. Includes runtime, handler, memory, timeout, and IAM role.

### Invocation Types

| Type | Description | Use Case |
|------|-------------|----------|
| **Synchronous** | Caller waits for response | API Gateway, direct invoke |
| **Asynchronous** | Fire and forget | S3, SNS, EventBridge |
| **Poll-based** | Lambda polls source | SQS, Kinesis, DynamoDB Streams |

### Execution Environment

Lambda creates execution environments to run your function. Components:
- **Cold start**: New environment initialization
- **Warm start**: Reusing existing environment
- **Handler**: Entry point function
- **Context**: Runtime information

### Layers

Reusable packages of libraries, dependencies, or custom runtimes (up to 5 per function).

## Common Patterns

### Create a Python Function

**AWS CLI:**

```bash
# Create deployment package
zip function.zip lambda_function.py

# Create function
aws lambda create-function \
  --function-name MyFunction \
  --runtime python3.12 \
  --role arn:aws:iam::123456789012:role/lambda-role \
  --handler lambda_function.handler \
  --zip-file fileb://function.zip \
  --timeout 30 \
  --memory-size 256

# Update function code
aws lambda update-function-code \
  --function-name MyFunction \
  --zip-file fileb://function.zip
```

**boto3:**

```python
import boto3
import zipfile
import io

lambda_client = boto3.client('lambda')

# Create zip in memory
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zf:
    zf.writestr('lambda_function.py', '''
def handler(event, context):
    return {"statusCode": 200, "body": "Hello"}
''')
zip_buffer.seek(0)

# Create function
lambda_client.create_function(
    FunctionName='MyFunction',
    Runtime='python3.12',
    Role='arn:aws:iam::123456789012:role/lambda-role',
    Handler='lambda_function.handler',
    Code={'ZipFile': zip_buffer.read()},
    Timeout=30,
    MemorySize=256
)
```

### Add S3 Trigger

```bash
# Add permission for S3 to invoke Lambda
aws lambda add-permission \
  --function-name MyFunction \
  --statement-id s3-trigger \
  --action lambda:InvokeFunction \
  --principal s3.amazonaws.com \
  --source-arn arn:aws:s3:::my-bucket \
  --source-account 123456789012

# Configure S3 notification (see S3 skill)
```

### Add SQS Event Source

```bash
aws lambda create-event-source-mapping \
  --function-name MyFunction \
  --event-source-arn arn:aws:sqs:us-east-1:123456789012:my-queue \
  --batch-size 10 \
  --maximum-batching-window-in-seconds 5
```

### Environment Variables

```bash
aws lambda update-function-configuration \
  --function-name MyFunction \
  --environment "Variables={DB_HOST=mydb.cluster-xyz.us-east-1.rds.amazonaws.com,LOG_LEVEL=INFO}"
```

### Create and Attach Layer

```bash
# Create layer
zip -r layer.zip python/

aws lambda publish-layer-version \
  --layer-name my-dependencies \
  --compatible-runtimes python3.12 \
  --zip-file fileb://layer.zip

# Attach to function
aws lambda update-function-configuration \
  --function-name MyFunction \
  --layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
```

### Invoke Function

```bash
# Synchronous invoke
aws lambda invoke \
  --function-name MyFunction \
  --payload '{"key": "value"}' \
  response.json

# Asynchronous invoke
aws lambda invoke \
  --function-name MyFunction \
  --invocation-type Event \
  --payload '{"key": "value"}' \
  response.json
```

## CLI Reference

### Function Management

| Command | Description |
|---------|-------------|
| `aws lambda create-function` | Create new function |
| `aws lambda update-function-code` | Update function code |
| `aws lambda update-function-configuration` | Update settings |
| `aws lambda delete-function` | Delete function |
| `aws lambda list-functions` | List all functions |
| `aws lambda get-function` | Get function details |

### Invocation

| Command | Description |
|---------|-------------|
| `aws lambda invoke` | Invoke function |
| `aws lambda invoke-async` | Async invoke (deprecated) |

### Event Sources

| Command | Description |
|---------|-------------|
| `aws lambda create-event-source-mapping` | Add event source |
| `aws lambda list-event-source-mappings` | List mappings |
| `aws lambda update-event-source-mapping` | Update mapping |
| `aws lambda delete-event-source-mapping` | Remove mapping |

### Permissions

| Command | Description |
|---------|-------------|
| `aws lambda add-permission` | Add resource-based policy |
| `aws lambda remove-permission` | Remove permission |
| `aws lambda get-policy` | View resource policy |

## Best Practices

### Performance

- **Right-size memory**: More memory = more CPU = faster execution
- **Minimize cold starts**: Keep functions warm, use Provisioned Concurrency
- **Optimize package size**: Smaller packages deploy faster
- **Use layers** for shared dependencies
- **Initialize outside handler**: Reuse connections across invocations

```python
# GOOD: Initialize outside handler
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')

def handler(event, context):
    # Reuses existing connection
    return table.get_item(Key={'id': event['id']})
```

### Security

- **Least privilege IAM roles** — only grant needed permissions
- **Use Secrets Manager** for sensitive data
- **Enable VPC** only if needed (adds latency)
- **Encrypt environment variables** with KMS

### Cost Optimization

- **Set appropriate timeout** — don't use max 15 minutes unnecessarily
- **Use ARM architecture** (Graviton2) for 34% better price/
api-gatewaySkill

AWS API Gateway for REST and HTTP API management. Use when creating APIs, configuring integrations, setting up authorization, managing stages, implementing rate limiting, or troubleshooting API issues.

bedrockSkill

AWS Bedrock foundation models for generative AI. Use when invoking foundation models, building AI applications, creating embeddings, configuring model access, or implementing RAG patterns.

cloudformationSkill

AWS CloudFormation infrastructure as code for stack management. Use when writing templates, deploying stacks, managing drift, troubleshooting deployments, or organizing infrastructure with nested stacks.

cloudwatchSkill

AWS CloudWatch monitoring for logs, metrics, alarms, and dashboards. Use when setting up monitoring, creating alarms, querying logs with Insights, configuring metric filters, building dashboards, or troubleshooting application issues.

cognitoSkill

AWS Cognito user authentication and authorization service. Use when setting up user pools, configuring identity pools, implementing OAuth flows, managing user attributes, or integrating with social identity providers.

dynamodbSkill

AWS DynamoDB NoSQL database for scalable data storage. Use when designing table schemas, writing queries, configuring indexes, managing capacity, implementing single-table design, or troubleshooting performance issues.

ec2Skill

>

ecsSkill

AWS ECS container orchestration for running Docker containers. Use when deploying containerized applications, configuring task definitions, setting up services, managing clusters, or troubleshooting container issues.