Context Strategy
The Context Strategy is a powerful pattern for managing multi-environment deployments with environment-specific configurations.
Overview
The ContextStrategy class provides a robust way to:
- Validate and normalize environment stages (dev, staging, prod, test, qa, preprod)
- Map stages to core environments (dev, staging, prod)
- Access environment context throughout your CDK application
- Ensure type-safe environment configuration
SDLC Environments
The library supports six SDLC environments that map to three core environments:
| SDLC Environment | Core Environment | Use Case |
|---|---|---|
dev | dev | Development and feature testing |
test | dev | Automated testing |
staging | staging | Pre-production validation |
qa | staging | Quality assurance testing |
preprod | staging | Final production validation |
prod | prod | Production environment |
Basic Usage
In Your CDK App
import { App } from '@root/aws-cdk-lib';
const app = new App();
// Get the SDLC environment from context
const sdlc = app.contextStrategy.getStageType();
// Use it in your stack
new MyStack(app, `MyStack-${sdlc}`, {
sdlc,
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});
Deploying to Different Environments
Deploy to different environments by passing the stage context:
# Deploy to development
cdk deploy --context stage=dev
# Deploy to staging
cdk deploy --context stage=staging
# Deploy to production
cdk deploy --context stage=prod
Using Context Strategy in Constructs
Access the context strategy from any construct:
import { Construct } from 'constructs';
import { ContextStrategy } from '@root/index';
export class MyConstruct extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
// Get context strategy from construct scope
const contextStrategy = new ContextStrategy(this);
const sdlc = contextStrategy.getStageType();
const sdlcCore = contextStrategy.getSdlcCore();
console.log(`Deploying to ${sdlc} (core: ${sdlcCore})`);
}
}
Environment-Specific Configuration
Use the context strategy to apply environment-specific settings:
import { getSdlcConfig } from '@root/types/defaults';
const config = getSdlcConfig(sdlc);
// Access environment-specific configuration
const lambdaTimeout = config.lambda.timeout;
const logRetention = config.lambda.logRetentionDays;
const errorThreshold = config.alarm.errorThreshold;
Default Configurations by Environment
The library provides sensible defaults for each core environment:
Development (dev, test)
- Lambda timeout: 30 seconds
- Memory: 256 MB
- Log retention: 3 days
- Deployment: All-at-once
- Error threshold: 5 errors
Staging (staging, qa, preprod)
- Lambda timeout: 60 seconds
- Memory: 512 MB
- Log retention: 7 days
- Deployment: Canary with 10% traffic shift
- Error threshold: 3 errors
Production (prod)
- Lambda timeout: 60 seconds
- Memory: 1024 MB
- Log retention: 30 days
- Deployment: Linear with 10% every 10 minutes
- Error threshold: 1 error
Validation and Error Handling
The Context Strategy validates stage values and throws descriptive errors:
try {
const sdlc = ContextStrategy.validateSDLCStage('invalid');
} catch (error) {
// ContextStrategyValidationError: Invalid stage 'invalid'.
// Allowed stages are: dev, staging, prod, test, qa, preprod
}
Stage Normalization
The context strategy automatically normalizes stage names:
# All of these normalize to 'dev'
cdk deploy --context stage=dev
cdk deploy --context stage=dev-feature-123
cdk deploy --context stage=dev-hotfix
The normalizer takes the first word before any non-alphanumeric character.
Core Environment Mapping
Access the core environment for simplified logic:
const sdlcCore = contextStrategy.getSdlcCore();
if (sdlcCore === 'prod') {
// Production-specific configuration
enableStrictMonitoring();
} else {
// Non-production environments
enableDebugMode();
}
CI/CD Integration
GitHub Actions
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to Dev
if: github.ref == 'refs/heads/develop'
run: npm run deploy -- --context stage=dev
- name: Deploy to Staging
if: github.ref == 'refs/heads/main'
run: npm run deploy -- --context stage=staging
- name: Deploy to Production
if: startsWith(github.ref, 'refs/tags/v')
run: npm run deploy -- --context stage=prod
Best Practices
- Always specify stage context: Never rely on default stage values
- Use core environments for branching logic: Simplify conditional logic by using
sdlcCore - Leverage environment-specific configs: Use
getSdlcConfig()for consistent settings - Name resources with stage suffix: Include
${sdlc}in resource names for clarity - Test stage validation: Ensure your CI/CD properly passes stage context
API Reference
ContextStrategy Class
Constructor
new ContextStrategy(scope: Construct)
Methods
getStageType(): Returns the SDLC environment (e.g., 'dev', 'staging', 'prod')getSdlcCore(): Returns the core environment ('dev', 'staging', or 'prod')getContext(): Returns the raw context stringstatic validateSDLCStage(stage: string): Validates a stage string
Related
- Blue-Green Deployments - Learn how Context Strategy integrates with deployment patterns
- Lambda Patterns - See Context Strategy in action with Lambda functions