AWS Serverless Deployment
AWS LabsOfficialPublished by AWS Labs
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to deploying serverless applications on AWS. It supports both AWS SAM and AWS CDK, offering guidance on project scaffolding, IaC template management, Lambda function constructs, and CI/CD pipeline integration. It includes best practices for resource configuration, environment management, and testing, while providing specific hooks for SAM template validation and automated deployment workflows.
What it does
- Provides project scaffolding for both SAM and CDK serverless applications.
- Offers guidance on using L2 CDK constructs for optimized Lambda function deployment.
- Automates SAM template validation via a post-edit hook.
- Supports multi-environment deployment strategies using configuration files.
- Facilitates the integration of CI/CD pipelines for serverless infrastructure.
- Provides reference material for SAM and CDK coexistence and migration.
When to use it
- When initializing a new serverless project on AWS.
- When you need to define Lambda functions using optimized CDK constructs like NodejsFunction.
- When you require automated validation for your SAM templates.
- When setting up infrastructure-as-code for serverless resources like DynamoDB, SQS, or API Gateway.
- When migrating or managing a project that uses both SAM and CDK.
Advantages
- Promotes the use of L2 constructs for safer, least-privilege IAM policies.
- Enables type-safe infrastructure development using TypeScript with CDK.
- Reduces manual errors through automated template validation.
- Simplifies complex resource wiring with pre-defined serverless patterns.
- Supports deterministic synthesis through cached context files.
Usage examples
- “Initialize a new serverless project using CDK with TypeScript.”
- The agent will guide you through the cdk init process, setting up the project structure with bin, lib, and test directories.
- “How do I define a Lambda function in CDK using NodejsFunction?”
- The agent will provide a code snippet demonstrating the NodejsFunction construct, including configuration for runtime, memory, and esbuild bundling.
- “Validate my current SAM template.”
- The agent will trigger the sam validate command to check your template.yaml for syntax and configuration errors.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/awslabs/aws-serverless-deployment/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip aws-serverless-deployment.zip -d .agents/skills
Documentation by AWS Labs
AWS Serverless Deployment
Deploy serverless applications to AWS using SAM or CDK. This skill covers project scaffolding, IaC templates, CDK constructs and patterns, deployment workflows, CI/CD pipelines, and SAM/CDK coexistence.
For Lambda runtime behavior, event sources, orchestration, observability, and optimization, see the aws-lambda skill.
When to Load Reference Files
Load the appropriate reference file based on what the user is working on:
SAM project setup, templates, deployment workflow, local testing, or container images -> see references/sam-project-setup.md
CDK project setup, constructs, CDK testing, or CDK pipelines -> see references/cdk-project-setup.md
CDK Lambda constructs, NodejsFunction, PythonFunction, or CDK Function -> see references/cdk-lambda-constructs.md
CDK serverless patterns, API Gateway CDK, Function URL CDK, EventBridge CDK, DynamoDB CDK, or SQS CDK -> see references/cdk-serverless-patterns.md
SAM and CDK coexistence, migrating from SAM to CDK, or using sam build with CDK -> see references/sam-cdk-coexistence.md
Best Practices
SAM
Do: Use
sam_initwith an appropriate template for your use caseDo: Set global defaults for timeout, memory, runtime, and tracing in the
GlobalssectionDo: Use
samconfig.tomlenvironment-specific sections for multi-environment deploymentsDo: Use
sam build --use-containerwhen native dependencies are involvedDon't: Copy-paste templates from the internet without understanding the resource configuration
Don't: Hardcode resource ARNs or account IDs in templates — use
!Ref,!GetAtt, and!Sub
CDK
Do: Use TypeScript — type checking catches errors at synthesis time, before any AWS API calls
Do: Prefer L2 constructs and
grant*methods over L1 and raw IAM statementsDo: Separate stateful and stateless resources into different stacks; enable termination protection on stateful stacks
Do: Commit
cdk.context.jsonto version control — it caches VPC/AZ lookups for deterministic synthesisDo: Write unit tests with
aws-cdk-lib/assertions; assert logical IDs of stateful resources to detect accidental replacementsDo: Use
cdk diffin CI before every deployment to review changesDon't: Hardcode account IDs or region strings — use
this.accountandthis.regionDon't: Use
cdk deploydirectly in production without a pipelineDon't: Skip
cdk bootstrap— deployments will fail without the CDK toolkit stack
Configuration
AWS CLI Setup
This skill requires that AWS credentials are configured on the host machine:
Verify access: Run aws sts get-caller-identity to confirm credentials are valid
SAM CLI Setup
Verify: Run sam --version
Container Runtime Setup
Install a Docker compatible container runtime: Required for
sam_local_invokeand container-based buildsVerify: Use an appropriate command such as
docker --versionorfinch --version
AWS Serverless MCP Server
Write access is enabled by default. The plugin ships with --allow-write in .mcp.json, so the MCP server can create projects, generate IaC, and deploy on behalf of the user.
Access to sensitive data (like Lambda and API Gateway logs) is not enabled by default. To grant it, add --allow-sensitive-data-access to .mcp.json.
SAM Template Validation Hook
This plugin includes a PostToolUse hook that runs sam validate automatically after any edit to template.yaml or template.yml. If validation fails, the error is returned as a system message so you can fix it immediately. The hook requires SAM CLI and jq to be installed; if either is missing, validation is skipped with a system message. Users can disable it via /hooks.
Verify: Run jq --version
IaC framework selection
Default: CDK
Override syntax:
"use CloudFormation" → Generate YAML templates
"use SAM" → Generate YAML templates
When not specified, ALWAYS use CDK
Language selection for CDK
Default: TypeScript
Override syntax:
"use Python" → Generate Python code
"use JavaScript" → Generate JavaScript code
When not specified, ALWAYS use TypeScript
Error Scenarios
Serverless MCP Server Unavailable
Inform user: "AWS Serverless MCP not responding"
Ask: "Proceed without MCP support?"
DO NOT continue without user confirmation
Resources
Files
- ATTRIBUTION.mdAdded by AutoGineer936 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer89 B
- SKILL.md5.2 KiB
- references/cdk-lambda-constructs.md3.3 KiB
- references/cdk-project-setup.md11.4 KiB
- references/cdk-serverless-patterns.md4.4 KiB
- references/sam-cdk-coexistence.md2.7 KiB
- references/sam-project-setup.md13.0 KiB
references/cdk-project-setup.md
CDK Project Setup Guide
SAM vs CDK: When to Use Each
Both SAM and CDK synthesize CloudFormation. Choosing between them is a matter of team preference and project context.
| SAM | CDK | |
|---|---|---|
| Language | YAML/JSON (declarative) | TypeScript, Python, Java, Go, C# (imperative) |
| Learning curve | Lower — close to CloudFormation | Higher — requires familiarity with a programming language |
| Abstraction level | Handles wiring for Serverless resources | Rich L2/L3 constructs handle wiring automatically |
| Code sharing | Template fragments only | Full reuse via construct libraries (npm, PyPI) |
| Loops and conditions | Limited | Native language constructs (for, if, maps) |
| Testing | Manual template review | Unit tests with aws-cdk-lib/assertions |
| Best for | Lambda-centric apps, teams new to IaC | Large teams building reusable infrastructure patterns |
Choose SAM when your primary concern is Lambda functions and you want the SAM MCP tools.
Choose CDK when you have complex infrastructure, want to write reusable construct libraries, prefer a programming-language interface, or your team already uses CDK elsewhere.
Both tools support the get_iac_guidance MCP tool for additional context:
get_iac_guidance(iac_tool: "cdk")Getting Started
Install and Bootstrap
npm install -g aws-cdk
cdk --version
# One-time account/region bootstrap (creates CDK toolkit stack)
cdk bootstrap aws://ACCOUNT-ID/REGIONInitialize a New Project
mkdir my-serverless-app && cd my-serverless-app
cdk init app --language typescript
npm installProject Structure
my-serverless-app/
├── bin/
│ └── my-serverless-app.ts # App entry point
├── lib/
│ └── my-serverless-app-stack.ts # Stack definition
├── lambda/
│ └── handler.ts # Lambda function code
├── test/
│ └── my-serverless-app.test.ts
├── cdk.context.json # Committed to git — caches lookups
├── cdk.json # CDK config
└── tsconfig.jsonConstruct Levels
CDK has three levels of constructs:
| Level | Description | Example |
|---|---|---|
| _L1 (Cfn)_* | Direct CloudFormation resource, 1:1 mapping | CfnFunction, CfnTable |
| L2 | Opinionated wrapper with sensible defaults and helper methods | Function, Table, Queue |
| L3 (Patterns) | Complete patterns that wire multiple resources together | LambdaRestApi, SqsEventSource |
Always prefer L2 constructs. Use L1 only when a feature is missing from the L2. Use L3 patterns as a starting point, but understand what they create.
Lambda Functions
For CDK Lambda function constructs — NodejsFunction (TypeScript/JavaScript with esbuild), PythonFunction (alpha, Docker-based), and base Function (Java, Go, .NET) — see cdk-lambda-constructs.md.
IAM with grant* Methods
CDK L2 constructs expose grant* methods that generate least-privilege policies automatically. Prefer these over writing raw PolicyStatement objects.
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as events from 'aws-cdk-lib/aws-events';
// DynamoDB
table.grantReadWriteData(myFunction);
table.grantReadData(readOnlyFunction);
// S3
bucket.grantRead(myFunction);
bucket.grantPut(myFunction);
// SQS
queue.grantSendMessages(myFunction);
queue.grantConsumeMessages(myFunction);
// EventBridge — put events
eventBus.grantPutEventsTo(myFunction);
// Lambda — invoke another function
otherFunction.grantInvoke(myFunction);
// Secrets Manager
secret.grantRead(myFunction);For resources not covered by grant*, add a PolicyStatement directly:
import * as iam from 'aws-cdk-lib/aws-iam';
myFunction.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['bedrock:InvokeModel'],
resources: [`arn:aws:bedrock:${this.region}::foundation-model/anthropic.claude-3-sonnet*`],
}));Common Serverless Patterns
For CDK code examples of common serverless patterns — API Gateway HTTP API, Lambda Function URL, EventBridge custom bus, DynamoDB table, and SQS queue with Lambda — see cdk-serverless-patterns.md.
Separating Stateful and Stateless Stacks
Stateful resources (databases, queues, S3 buckets, event buses) should be in a separate stack with termination protection. This prevents accidental deletion during routine deployments.
// bin/my-app.ts
const app = new cdk.App();
// Stateful stack — deployed once, termination-protected
const stateful = new StatefulStack(app, 'StatefulStack', {
env: { account: '123456789012', region: 'us-east-1' },
terminationProtection: true,
});
// Stateless stack — deployed on every code change
const stateless = new StatelessStack(app, 'StatelessStack', {
env: { account: '123456789012', region: 'us-east-1' },
// Pass references from stateful stack
ordersTable: stateful.ordersTable,
orderEventBus: stateful.orderEventBus,
});// lib/stateful-stack.ts
export class StatefulStack extends cdk.Stack {
public readonly ordersTable: dynamodb.Table;
public readonly orderEventBus: events.EventBus;
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
this.ordersTable = new dynamodb.Table(this, 'OrdersTable', {
// ...
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
this.orderEventBus = new events.EventBus(this, 'OrderEventBus', {
eventBusName: 'order-events',
});
}
}CDK Testing
CDK constructs can be unit tested without deploying. Use aws-cdk-lib/assertions with Jest.
npm install --save-dev jest @types/jest ts-jest// test/order-stack.test.ts
import * as cdk from 'aws-cdk-lib';
import { Template, Match } from 'aws-cdk-lib/assertions';
import { OrderStack } from '../lib/order-stack';
describe('OrderStack', () => {
let template: Template;
beforeEach(() => {
const app = new cdk.App();
const stack = new OrderStack(app, 'TestOrderStack');
template = Template.fromStack(stack);
});
it('creates Lambda function with ARM64 architecture', () => {
template.hasResourceProperties('AWS::Lambda::Function', {
Architectures: ['arm64'],
Runtime: 'nodejs22.x',
});
});
it('grants DynamoDB read-write to order handler', () => {
template.hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
Statement: Match.arrayWith([
Match.objectLike({
Action: Match.arrayWith([
'dynamodb:GetItem',
'dynamodb:PutItem',
]),
}),
]),
},
});
});
it('has exactly one DynamoDB table', () => {
template.resourceCountIs('AWS::DynamoDB::Table', 1);
});
it('DynamoDB table has retention policy', () => {
template.hasResource('AWS::DynamoDB::Table', {
DeletionPolicy: 'Retain',
});
});
});Assert logical IDs of stateful resources to catch accidental replacements early — renaming a CDK construct ID causes CloudFormation to delete and recreate the resource:
it('orders table logical ID is stable', () => {
const resources = template.findResources('AWS::DynamoDB::Table');
expect(Object.keys(resources)).toContain('OrdersTable1234ABCD'); // update if intentionally renamed
});Deployment Workflow
# Synthesize CloudFormation template (runs assertions, no AWS calls)
cdk synth
# Preview changes before deploying
cdk diff
# Deploy all stacks
cdk deploy --all
# Deploy a specific stack
cdk deploy StatelessStack
# Deploy with approval prompt disabled (CI/CD)
cdk deploy --require-approval never
# Destroy a stack (respects RemovalPolicy — RETAIN resources are kept)
cdk destroy StatelessStackCDK Pipelines (CI/CD)
CDK Pipelines is a self-mutating CI/CD pipeline construct built on CodePipeline.
import { CodePipeline, CodePipelineSource, ManualApprovalStep, ShellStep } from 'aws-cdk-lib/pipelines';
export class PipelineStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const pipeline = new CodePipeline(this, 'Pipeline', {
pipelineName: 'MyServerlessPipeline',
synth: new ShellStep('Synth', {
input: CodePipelineSource.gitHub('my-org/my-repo', 'main'),
commands: ['npm ci', 'npm run build', 'npx cdk synth'],
}),
});
// Staging stage
pipeline.addStage(new MyAppStage(this, 'Staging', {
env: { account: '111111111111', region: 'us-east-1' },
}));
// Production stage with manual approval
pipeline.addStage(new MyAppStage(this, 'Production', {
env: { account: '222222222222', region: 'us-east-1' },
}), {
pre: [new ManualApprovalStep('PromoteToProduction')],
});
}
}The pipeline updates itself: when you push changes to the pipeline stack, the next run applies them before deploying the application.
SAM and CDK Coexistence
For guidance on running SAM and CDK side by side — incremental migration, using sam build on CDK-synthesized templates, and when to use which — see sam-cdk-coexistence.md.
Best Practices
Do
Use TypeScript — type checking catches errors at synthesis time, before any AWS API calls
Prefer L2 constructs and
grant*methods over L1 and raw IAM statementsNever hardcode resource names — always reference generated names (
table.tableName,queue.queueUrl)Separate stateful and stateless resources into different stacks; enable termination protection on stateful stacks
Commit
cdk.context.jsonto version control — it caches VPC/AZ lookups for deterministic synthesisWrite unit tests with
aws-cdk-lib/assertions; assert logical IDs of stateful resources to detect accidental replacementsSet
RemovalPolicy.RETAINon all databases, S3 buckets, and event busesUse
cdk diffin CI before every deployment to review changesPass all configuration to constructs via props; never read environment variables inside construct constructors
Don't
Hardcode account IDs or region strings — use
this.accountandthis.regionUse
cdk deploydirectly in production without a pipelineSkip
cdk bootstrap— deployments will fail without the CDK toolkit stackRely on CloudFormation
ParametersandConditionswhen you can express the same logic in TypeScriptMix
RemovalPolicy.DESTROYinto shared/stateful stacksReference constructs across separate CDK apps using CloudFormation outputs if you can pass object references directly
Requirements and compatibility
Written for: Claude Code
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Claude Code frontmatter, Needs an MCP server
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS Labs
- Publisher
- AWS Labs (Official)
- Source
- awslabs/agent-plugins · plugins/aws-serverless/skills/aws-serverless-deployment · commit fbefb37
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by AWS Labs.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-serverless-deployment.zip