Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 09:08:41 +08:00
commit df90f04070
6 changed files with 1008 additions and 0 deletions

View File

@@ -0,0 +1,270 @@
---
name: aws-cdk-development
description: AWS Cloud Development Kit (CDK) expert for building cloud infrastructure with TypeScript/Python. Use when creating CDK stacks, defining CDK constructs, implementing infrastructure as code, or when the user mentions CDK, CloudFormation, IaC, cdk synth, cdk deploy, or wants to define AWS infrastructure programmatically. Covers CDK app structure, construct patterns, stack composition, and deployment workflows.
---
# AWS CDK Development
This skill provides comprehensive guidance for developing AWS infrastructure using the Cloud Development Kit (CDK), with integrated MCP servers for accessing latest AWS knowledge and CDK utilities.
## Integrated MCP Servers
This skill includes two MCP servers automatically configured with the plugin:
### AWS Documentation MCP Server
**When to use**: Always verify AWS service information before implementation
- Search AWS documentation for latest features and best practices
- Check regional availability of AWS services
- Verify service limits and quotas
- Confirm API specifications and parameters
- Access up-to-date AWS service information
**Critical**: Use this server whenever AWS service features, configurations, or availability need verification.
### AWS CDK MCP Server
**When to use**: For CDK-specific guidance and utilities
- Get CDK construct recommendations
- Retrieve CDK best practices
- Access CDK pattern suggestions
- Validate CDK configurations
- Get help with CDK-specific APIs
**Important**: Leverage this server for CDK construct guidance and advanced CDK operations.
## When to Use This Skill
Use this skill when:
- Creating new CDK stacks or constructs
- Refactoring existing CDK infrastructure
- Implementing Lambda functions within CDK
- Following AWS CDK best practices
- Validating CDK stack configurations before deployment
- Verifying AWS service capabilities and regional availability
## Core CDK Principles
### Resource Naming
**CRITICAL**: Do NOT explicitly specify resource names when they are optional in CDK constructs.
**Why**: CDK-generated names enable:
- **Reusable patterns**: Deploy the same construct/pattern multiple times without conflicts
- **Parallel deployments**: Multiple stacks can deploy simultaneously in the same region
- **Cleaner shared logic**: Patterns and shared code can be initialized multiple times without name collision
- **Stack isolation**: Each stack gets uniquely identified resources automatically
**Pattern**: Let CDK generate unique names automatically using CloudFormation's naming mechanism.
```typescript
// ❌ BAD - Explicit naming prevents reusability and parallel deployments
new lambda.Function(this, 'MyFunction', {
functionName: 'my-lambda', // Avoid this
// ...
});
// ✅ GOOD - Let CDK generate unique names
new lambda.Function(this, 'MyFunction', {
// No functionName specified - CDK generates: StackName-MyFunctionXXXXXX
// ...
});
```
**Security Note**: For different environments (dev, staging, prod), follow AWS Security Pillar best practices by using separate AWS accounts rather than relying on resource naming within a single account. Account-level isolation provides stronger security boundaries.
### Lambda Function Development
Use the appropriate Lambda construct based on runtime:
**TypeScript/JavaScript**: Use `@aws-cdk/aws-lambda-nodejs`
```typescript
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
new NodejsFunction(this, 'MyFunction', {
entry: 'lambda/handler.ts',
handler: 'handler',
// Automatically handles bundling, dependencies, and transpilation
});
```
**Python**: Use `@aws-cdk/aws-lambda-python`
```typescript
import { PythonFunction } from '@aws-cdk/aws-lambda-python-alpha';
new PythonFunction(this, 'MyFunction', {
entry: 'lambda',
index: 'handler.py',
handler: 'handler',
// Automatically handles dependencies and packaging
});
```
**Benefits**:
- Automatic bundling and dependency management
- Transpilation handled automatically
- No manual packaging required
- Consistent deployment patterns
### Pre-Deployment Validation
Use a **multi-layer validation strategy** for comprehensive CDK quality checks:
#### Layer 1: Real-Time IDE Feedback (Recommended)
**For TypeScript/JavaScript projects**:
Install [cdk-nag](https://github.com/cdklabs/cdk-nag) for synthesis-time validation:
```bash
npm install --save-dev cdk-nag
```
Add to your CDK app:
```typescript
import { Aspects } from 'aws-cdk-lib';
import { AwsSolutionsChecks } from 'cdk-nag';
const app = new App();
Aspects.of(app).add(new AwsSolutionsChecks());
```
**Optional - VS Code users**: Install [CDK NAG Validator extension](https://marketplace.visualstudio.com/items?itemName=alphacrack.cdk-nag-validator) for faster feedback on file save.
**For Python/Java/C#/Go projects**: cdk-nag is available in all CDK languages and provides the same synthesis-time validation.
#### Layer 2: Synthesis-Time Validation (Required)
1. **Synthesis with cdk-nag**: Validate stack with comprehensive rules
```bash
cdk synth # cdk-nag runs automatically via Aspects
```
2. **Suppress legitimate exceptions** with documented reasons:
```typescript
import { NagSuppressions } from 'cdk-nag';
// Document WHY the exception is needed
NagSuppressions.addResourceSuppressions(resource, [
{
id: 'AwsSolutions-L1',
reason: 'Lambda@Edge requires specific runtime for CloudFront compatibility'
}
]);
```
#### Layer 3: Pre-Commit Safety Net
1. **Build**: Ensure compilation succeeds
```bash
npm run build # or language-specific build command
```
2. **Tests**: Run unit and integration tests
```bash
npm test # or pytest, mvn test, etc.
```
3. **Validation Script**: Meta-level checks
```bash
./scripts/validate-stack.sh
```
The validation script now focuses on:
- Language detection
- Template size and resource count analysis
- Synthesis success verification
- (Note: Detailed anti-pattern checks are handled by cdk-nag)
## Workflow Guidelines
### Development Workflow
1. **Design**: Plan infrastructure resources and relationships
2. **Verify AWS Services**: Use AWS Documentation MCP to confirm service availability and features
- Check regional availability for all required services
- Verify service limits and quotas
- Confirm latest API specifications
3. **Implement**: Write CDK constructs following best practices
- Use CDK MCP server for construct recommendations
- Reference CDK best practices via MCP tools
4. **Validate**: Run pre-deployment checks (see above)
5. **Synthesize**: Generate CloudFormation templates
6. **Review**: Examine synthesized templates for correctness
7. **Deploy**: Deploy to target environment
8. **Verify**: Confirm resources are created correctly
### Stack Organization
- Use nested stacks for complex applications
- Separate concerns into logical construct boundaries
- Export values that other stacks may need
- Use CDK context for environment-specific configuration
### Testing Strategy
- Unit test individual constructs
- Integration test stack synthesis
- Snapshot test CloudFormation templates
- Validate resource properties and relationships
## Using MCP Servers Effectively
### When to Use AWS Documentation MCP
**Always verify before implementing**:
- New AWS service features or configurations
- Service availability in target regions
- API parameter specifications
- Service limits and quotas
- Security best practices for AWS services
**Example scenarios**:
- "Check if Lambda supports Python 3.13 runtime"
- "Verify DynamoDB is available in eu-south-2"
- "What are the current Lambda timeout limits?"
- "Get latest S3 encryption options"
### When to Use CDK MCP Server
**Leverage for CDK-specific guidance**:
- CDK construct selection and usage
- CDK API parameter options
- CDK best practice patterns
- Construct property configurations
- CDK-specific optimizations
**Example scenarios**:
- "What's the recommended CDK construct for API Gateway REST API?"
- "How to configure NodejsFunction bundling options?"
- "Best practices for CDK stack organization"
- "CDK construct for DynamoDB with auto-scaling"
### MCP Usage Best Practices
1. **Verify First**: Always check AWS Documentation MCP before implementing new features
2. **Regional Validation**: Check service availability in target deployment regions
3. **CDK Guidance**: Use CDK MCP for construct-specific recommendations
4. **Stay Current**: MCP servers provide latest information beyond knowledge cutoff
5. **Combine Sources**: Use both skill patterns and MCP servers for comprehensive guidance
## CDK Patterns Reference
For detailed CDK patterns, anti-patterns, and architectural guidance, refer to the comprehensive reference:
**File**: `references/cdk-patterns.md`
This reference includes:
- Common CDK patterns and their use cases
- Anti-patterns to avoid
- Security best practices
- Cost optimization strategies
- Performance considerations
## Additional Resources
- **Validation Script**: `scripts/validate-stack.sh` - Pre-deployment validation
- **CDK Patterns**: `references/cdk-patterns.md` - Detailed pattern library
- **AWS Documentation MCP**: Integrated for latest AWS information
- **CDK MCP Server**: Integrated for CDK-specific guidance
## GitHub Actions Integration
When GitHub Actions workflow files exist in the repository, ensure all checks defined in `.github/workflows/` pass before committing. This prevents CI/CD failures and maintains code quality standards.

View File

@@ -0,0 +1,431 @@
# AWS CDK Patterns and Best Practices
This reference provides detailed patterns, anti-patterns, and best practices for AWS CDK development.
## Table of Contents
- [Naming Conventions](#naming-conventions)
- [Construct Patterns](#construct-patterns)
- [Security Patterns](#security-patterns)
- [Lambda Integration](#lambda-integration)
- [Testing Patterns](#testing-patterns)
- [Cost Optimization](#cost-optimization)
- [Anti-Patterns](#anti-patterns)
## Naming Conventions
### Automatic Resource Naming (Recommended)
Let CDK and CloudFormation generate unique resource names automatically:
**Benefits**:
- Enables multiple deployments in the same region/account
- Supports parallel environments (dev, staging, prod)
- Prevents naming conflicts
- Allows stack cloning and testing
**Example**:
```typescript
// ✅ GOOD - Automatic naming
const bucket = new s3.Bucket(this, 'DataBucket', {
// No bucketName specified
encryption: s3.BucketEncryption.S3_MANAGED,
});
```
### When Explicit Naming is Required
Some scenarios require explicit names:
- Resources referenced by external systems
- Resources that must maintain consistent names across deployments
- Cross-stack references requiring stable names
**Pattern**: Use logical prefixes and environment suffixes
```typescript
// Only when absolutely necessary
const bucket = new s3.Bucket(this, 'DataBucket', {
bucketName: `${props.projectName}-data-${props.environment}`,
});
```
## Construct Patterns
### L3 Constructs (Patterns)
Prefer high-level patterns that encapsulate best practices:
```typescript
import * as patterns from 'aws-cdk-lib/aws-apigateway';
new patterns.LambdaRestApi(this, 'MyApi', {
handler: myFunction,
// Includes CloudWatch Logs, IAM roles, and API Gateway configuration
});
```
### Custom Constructs
Create reusable constructs for repeated patterns:
```typescript
export class ApiWithDatabase extends Construct {
public readonly api: apigateway.RestApi;
public readonly table: dynamodb.Table;
constructor(scope: Construct, id: string, props: ApiWithDatabaseProps) {
super(scope, id);
this.table = new dynamodb.Table(this, 'Table', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
});
const handler = new NodejsFunction(this, 'Handler', {
entry: props.handlerEntry,
environment: {
TABLE_NAME: this.table.tableName,
},
});
this.table.grantReadWriteData(handler);
this.api = new apigateway.LambdaRestApi(this, 'Api', {
handler,
});
}
}
```
## Security Patterns
### IAM Least Privilege
Use grant methods instead of broad policies:
```typescript
// ✅ GOOD - Specific grants
const table = new dynamodb.Table(this, 'Table', { /* ... */ });
const lambda = new lambda.Function(this, 'Function', { /* ... */ });
table.grantReadWriteData(lambda);
// ❌ BAD - Overly broad permissions
lambda.addToRolePolicy(new iam.PolicyStatement({
actions: ['dynamodb:*'],
resources: ['*'],
}));
```
### Secrets Management
Use Secrets Manager for sensitive data:
```typescript
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
const secret = new secretsmanager.Secret(this, 'DbPassword', {
generateSecretString: {
secretStringTemplate: JSON.stringify({ username: 'admin' }),
generateStringKey: 'password',
excludePunctuation: true,
},
});
// Grant read access to Lambda
secret.grantRead(myFunction);
```
### VPC Configuration
Follow VPC best practices:
```typescript
const vpc = new ec2.Vpc(this, 'Vpc', {
maxAzs: 2,
natGateways: 1, // Cost optimization: use 1 for dev, 2+ for prod
subnetConfiguration: [
{
name: 'Public',
subnetType: ec2.SubnetType.PUBLIC,
cidrMask: 24,
},
{
name: 'Private',
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
cidrMask: 24,
},
{
name: 'Isolated',
subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
cidrMask: 24,
},
],
});
```
## Lambda Integration
### NodejsFunction (TypeScript/JavaScript)
```typescript
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
const fn = new NodejsFunction(this, 'Function', {
entry: 'src/handlers/process.ts',
handler: 'handler',
runtime: lambda.Runtime.NODEJS_20_X,
timeout: Duration.seconds(30),
memorySize: 512,
environment: {
TABLE_NAME: table.tableName,
},
bundling: {
minify: true,
sourceMap: true,
externalModules: ['@aws-sdk/*'], // Use AWS SDK from Lambda runtime
},
});
```
### PythonFunction
```typescript
import { PythonFunction } from '@aws-cdk/aws-lambda-python-alpha';
const fn = new PythonFunction(this, 'Function', {
entry: 'src/handlers',
index: 'process.py',
handler: 'handler',
runtime: lambda.Runtime.PYTHON_3_12,
timeout: Duration.seconds(30),
memorySize: 512,
});
```
### Lambda Layers
Share code across functions:
```typescript
const layer = new lambda.LayerVersion(this, 'CommonLayer', {
code: lambda.Code.fromAsset('layers/common'),
compatibleRuntimes: [lambda.Runtime.NODEJS_20_X],
description: 'Common utilities',
});
new NodejsFunction(this, 'Function', {
entry: 'src/handler.ts',
layers: [layer],
});
```
## Testing Patterns
### Snapshot Testing
```typescript
import { Template } from 'aws-cdk-lib/assertions';
test('Stack creates expected resources', () => {
const app = new cdk.App();
const stack = new MyStack(app, 'TestStack');
const template = Template.fromStack(stack);
expect(template.toJSON()).toMatchSnapshot();
});
```
### Fine-Grained Assertions
```typescript
test('Lambda has correct environment', () => {
const app = new cdk.App();
const stack = new MyStack(app, 'TestStack');
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::Lambda::Function', {
Runtime: 'nodejs20.x',
Timeout: 30,
Environment: {
Variables: {
TABLE_NAME: { Ref: Match.anyValue() },
},
},
});
});
```
### Resource Count Validation
```typescript
test('Stack has correct number of functions', () => {
const app = new cdk.App();
const stack = new MyStack(app, 'TestStack');
const template = Template.fromStack(stack);
template.resourceCountIs('AWS::Lambda::Function', 3);
});
```
## Cost Optimization
### Right-Sizing Lambda
```typescript
// Development
const devFunction = new NodejsFunction(this, 'DevFunction', {
memorySize: 256, // Lower for dev
timeout: Duration.seconds(30),
});
// Production
const prodFunction = new NodejsFunction(this, 'ProdFunction', {
memorySize: 1024, // Higher for prod performance
timeout: Duration.seconds(10),
reservedConcurrentExecutions: 10, // Prevent runaway costs
});
```
### DynamoDB Billing Modes
```typescript
// Development/Low Traffic
const devTable = new dynamodb.Table(this, 'DevTable', {
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
});
// Production/Predictable Load
const prodTable = new dynamodb.Table(this, 'ProdTable', {
billingMode: dynamodb.BillingMode.PROVISIONED,
readCapacity: 5,
writeCapacity: 5,
autoScaling: { /* ... */ },
});
```
### S3 Lifecycle Policies
```typescript
const bucket = new s3.Bucket(this, 'DataBucket', {
lifecycleRules: [
{
id: 'MoveToIA',
transitions: [
{
storageClass: s3.StorageClass.INFREQUENT_ACCESS,
transitionAfter: Duration.days(30),
},
{
storageClass: s3.StorageClass.GLACIER,
transitionAfter: Duration.days(90),
},
],
},
{
id: 'CleanupOldVersions',
noncurrentVersionExpiration: Duration.days(30),
},
],
});
```
## Anti-Patterns
### ❌ Hardcoded Values
```typescript
// BAD
new lambda.Function(this, 'Function', {
functionName: 'my-function', // Prevents multiple deployments
code: lambda.Code.fromAsset('lambda'),
handler: 'index.handler',
runtime: lambda.Runtime.NODEJS_20_X,
});
// GOOD
new NodejsFunction(this, 'Function', {
entry: 'src/handler.ts',
// Let CDK generate the name
});
```
### ❌ Overly Broad IAM Permissions
```typescript
// BAD
function.addToRolePolicy(new iam.PolicyStatement({
actions: ['*'],
resources: ['*'],
}));
// GOOD
table.grantReadWriteData(function);
```
### ❌ Manual Dependency Management
```typescript
// BAD - Manual bundling
new lambda.Function(this, 'Function', {
code: lambda.Code.fromAsset('lambda.zip'), // Pre-bundled manually
// ...
});
// GOOD - Let CDK handle it
new NodejsFunction(this, 'Function', {
entry: 'src/handler.ts',
// CDK handles bundling automatically
});
```
### ❌ Missing Environment Variables
```typescript
// BAD
new NodejsFunction(this, 'Function', {
entry: 'src/handler.ts',
// Table name hardcoded in Lambda code
});
// GOOD
new NodejsFunction(this, 'Function', {
entry: 'src/handler.ts',
environment: {
TABLE_NAME: table.tableName,
},
});
```
### ❌ Ignoring Stack Outputs
```typescript
// BAD - No way to reference resources
new MyStack(app, 'Stack', {});
// GOOD - Export important values
class MyStack extends Stack {
constructor(scope: Construct, id: string) {
super(scope, id);
const api = new apigateway.RestApi(this, 'Api', {});
new CfnOutput(this, 'ApiUrl', {
value: api.url,
description: 'API Gateway URL',
exportName: 'MyApiUrl',
});
}
}
```
## Summary
- **Always** let CDK generate resource names unless explicitly required
- **Use** high-level constructs (L2/L3) over low-level (L1)
- **Prefer** grant methods for IAM permissions
- **Leverage** `NodejsFunction` and `PythonFunction` for automatic bundling
- **Test** stacks with assertions and snapshots
- **Optimize** costs based on environment (dev vs prod)
- **Validate** infrastructure before deployment
- **Document** custom constructs and patterns

View File

@@ -0,0 +1,240 @@
#!/bin/bash
# AWS CDK Stack Validation Script
#
# This script performs meta-level validation of CDK stacks before deployment.
# Run this as part of pre-commit checks to ensure infrastructure quality.
#
# Focus areas:
# - CDK synthesis success validation
# - CloudFormation template size and resource count checks
# - Language detection and dependency verification
# - Integration with cdk-nag (recommended for comprehensive best practice checks)
#
# Supports CDK projects in multiple languages:
# - TypeScript/JavaScript (detects via package.json)
# - Python (detects via requirements.txt or setup.py)
# - Java (detects via pom.xml)
# - C# (detects via .csproj files)
# - Go (detects via go.mod)
#
# For comprehensive CDK best practice validation (IAM policies, security,
# naming conventions, etc.), use cdk-nag: https://github.com/cdklabs/cdk-nag
# cdk-nag provides suppression mechanisms and supports all CDK languages.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"
echo "🔍 AWS CDK Stack Validation"
echo "============================"
echo ""
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Track validation status
VALIDATION_PASSED=true
# Function to print success
success() {
echo -e "${GREEN}${NC} $1"
}
# Function to print error
error() {
echo -e "${RED}${NC} $1"
VALIDATION_PASSED=false
}
# Function to print warning
warning() {
echo -e "${YELLOW}${NC} $1"
}
# Function to print info
info() {
echo " $1"
}
# Check if cdk is installed
if ! command -v cdk &> /dev/null; then
error "AWS CDK CLI not found. Install with: npm install -g aws-cdk"
exit 1
fi
success "AWS CDK CLI found"
# Detect CDK project language
detect_language() {
if [ -f "${PROJECT_ROOT}/package.json" ]; then
echo "typescript"
elif [ -f "${PROJECT_ROOT}/requirements.txt" ] || [ -f "${PROJECT_ROOT}/setup.py" ]; then
echo "python"
elif [ -f "${PROJECT_ROOT}/pom.xml" ]; then
echo "java"
elif [ -f "${PROJECT_ROOT}/cdk.csproj" ] || find "${PROJECT_ROOT}" -name "*.csproj" 2>/dev/null | grep -q .; then
echo "csharp"
elif [ -f "${PROJECT_ROOT}/go.mod" ]; then
echo "go"
else
echo "unknown"
fi
}
CDK_LANGUAGE=$(detect_language)
case "$CDK_LANGUAGE" in
typescript)
info "Detected TypeScript/JavaScript CDK project"
success "package.json found"
;;
python)
info "Detected Python CDK project"
success "requirements.txt or setup.py found"
;;
java)
info "Detected Java CDK project"
success "pom.xml found"
;;
csharp)
info "Detected C# CDK project"
success ".csproj file found"
;;
go)
info "Detected Go CDK project"
success "go.mod found"
;;
unknown)
warning "Could not detect CDK project language"
warning "Proceeding with generic validation only"
;;
esac
echo ""
info "Running CDK synthesis..."
# Synthesize stacks
if cdk synth --quiet > /dev/null 2>&1; then
success "CDK synthesis successful"
else
error "CDK synthesis failed"
echo ""
echo "Run 'cdk synth' for detailed error information"
exit 1
fi
echo ""
info "Checking for cdk-nag integration..."
# Check if cdk-nag is being used for comprehensive validation
case "$CDK_LANGUAGE" in
typescript)
if grep -r "cdk-nag" "${PROJECT_ROOT}/package.json" 2>/dev/null | grep -q "."; then
success "cdk-nag found in package.json"
else
warning "cdk-nag not found - recommended for comprehensive CDK validation"
warning "Install with: npm install --save-dev cdk-nag"
warning "See: https://github.com/cdklabs/cdk-nag"
fi
;;
python)
if grep -r "cdk-nag" "${PROJECT_ROOT}/requirements.txt" 2>/dev/null | grep -q "."; then
success "cdk-nag found in requirements.txt"
elif grep -r "cdk-nag" "${PROJECT_ROOT}/setup.py" 2>/dev/null | grep -q "."; then
success "cdk-nag found in setup.py"
else
warning "cdk-nag not found - recommended for comprehensive CDK validation"
warning "Install with: pip install cdk-nag"
warning "See: https://github.com/cdklabs/cdk-nag"
fi
;;
java)
if grep -r "cdk-nag" "${PROJECT_ROOT}/pom.xml" 2>/dev/null | grep -q "."; then
success "cdk-nag found in pom.xml"
else
warning "cdk-nag not found - recommended for comprehensive CDK validation"
warning "See: https://github.com/cdklabs/cdk-nag"
fi
;;
csharp)
if find "${PROJECT_ROOT}" -name "*.csproj" -exec grep -l "CdkNag" {} \; 2>/dev/null | grep -q "."; then
success "cdk-nag found in .csproj"
else
warning "cdk-nag not found - recommended for comprehensive CDK validation"
warning "See: https://github.com/cdklabs/cdk-nag"
fi
;;
go)
if grep -r "cdk-nag-go" "${PROJECT_ROOT}/go.mod" 2>/dev/null | grep -q "."; then
success "cdk-nag-go found in go.mod"
else
warning "cdk-nag-go not found - recommended for comprehensive CDK validation"
warning "See: https://github.com/cdklabs/cdk-nag-go"
fi
;;
esac
success "Integration checks completed"
echo ""
info "💡 Note: This script focuses on template and meta-level validation."
info "For comprehensive CDK best practice checks (IAM, security, naming, etc.),"
info "use cdk-nag: https://github.com/cdklabs/cdk-nag"
echo ""
info "Checking synthesized templates..."
# Get list of synthesized templates
TEMPLATES=$(find "${PROJECT_ROOT}/cdk.out" -name "*.template.json" 2>/dev/null || echo "")
if [ -z "$TEMPLATES" ]; then
error "No CloudFormation templates found in cdk.out/"
exit 1
fi
TEMPLATE_COUNT=$(echo "$TEMPLATES" | wc -l)
success "Found ${TEMPLATE_COUNT} CloudFormation template(s)"
# Validate each template
for template in $TEMPLATES; do
STACK_NAME=$(basename "$template" .template.json)
# Check template size
TEMPLATE_SIZE=$(wc -c < "$template")
MAX_SIZE=51200 # 50KB warning threshold
if [ "$TEMPLATE_SIZE" -gt "$MAX_SIZE" ]; then
warning "${STACK_NAME}: Template size (${TEMPLATE_SIZE} bytes) is large"
warning "Consider using nested stacks to reduce size"
fi
# Count resources
RESOURCE_COUNT=$(jq '.Resources | length' "$template" 2>/dev/null || echo 0)
if [ "$RESOURCE_COUNT" -gt 200 ]; then
warning "${STACK_NAME}: High resource count (${RESOURCE_COUNT})"
warning "Consider splitting into multiple stacks"
else
success "${STACK_NAME}: ${RESOURCE_COUNT} resources"
fi
done
echo ""
echo "============================"
if [ "$VALIDATION_PASSED" = true ]; then
echo -e "${GREEN}✓ Validation passed${NC}"
echo ""
info "Stack is ready for deployment"
exit 0
else
echo -e "${RED}✗ Validation failed${NC}"
echo ""
error "Please fix the errors above before deploying"
exit 1
fi