AWS CDK for Operations Teams: Constructs, Synth, Deploy, Diff and Pipelines Without Surprises
What CDK Is
AWS CDK lets you define infrastructure in TypeScript, Python, Java, C#, Go. The CDK app is synthesized into CloudFormation templates, and CloudFormation deploys them. So everything you know about stacks, change sets, rollbacks and drift still applies. CDK is on the newer SOA-C03 scope.
| Concept | Meaning |
| App | Root. Contains stacks |
| Stack | Unit of deployment = one CloudFormation stack |
| Construct | Building block. L1 (CfnBucket, raw CloudFormation), L2 (Bucket, sensible defaults and helper methods like grantRead), L3 patterns (ApplicationLoadBalancedFargateService) |
| Environment | Account + Region for a stack |
| Bootstrap | One-time setup per account/Region: creates the CDKToolkit stack with an S3 bucket, ECR repo and IAM roles for deployments |
| Assets | Local files, Lambda code and Docker images uploaded during deploy |
| Aspects | Visit all constructs to enforce rules (add tags, check encryption) |
Example in Python
python
from aws_cdk import App, Stack, Duration, RemovalPolicy, Tags
from aws_cdk import aws_s3 as s3, aws_lambda as _lambda, aws_events as events, aws_events_targets as targets, aws_cloudwatch as cw
from constructs import Construct
class OpsStack(Stack):
def __init__(self, scope: Construct, id: str, **kw):
super().__init__(scope, id, **kw)
bucket = s3.Bucket(self, "Reports", versioned=True, encryption=s3.BucketEncryption.S3_MANAGED,
block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
removal_policy=RemovalPolicy.RETAIN,
lifecycle_rules=[s3.LifecycleRule(expiration=Duration.days(365))])
fn = _lambda.Function(self, "Cleanup", runtime=_lambda.Runtime.PYTHON_3_12, handler="app.handler",
code=_lambda.Code.from_asset("lambda"), timeout=Duration.minutes(5),
environment={"BUCKET": bucket.bucket_name})
bucket.grant_read_write(fn) # creates least-privilege IAM automatically
events.Rule(self, "Nightly", schedule=events.Schedule.cron(minute="30", hour="20"), targets=[targets.LambdaFunction(fn)])
fn.metric_errors().create_alarm(self, "CleanupErrors", threshold=1, evaluation_periods=1)
app = App()
OpsStack(app, "OpsStack-prod", env={"account": "111111111111", "region": "ap-south-1"})
Tags.of(app).add("owner", "platform-team")
app.synth()
CDK Commands
bash
pm install -g aws-cdk
cdk init app --language python
cdk bootstrap aws://111111111111/ap-south-1
cdk synth # produce cdk.out/*.template.json
cdk diff # compare with deployed stack (like a change set)
cdk deploy OpsStack-prod --require-approval broadening
cdk deploy --all --hotswap # dev only: fast updates, bypasses CloudFormation
cdk destroy OpsStack-dev
cdk drift
cdk ls
- **
cdk diff before every deploy** and treat IAM and security group changes carefully (--require-approval prompts)
--hotswap is for development only. Do not use in production
- Use **
cdk watch** for fast dev loops
CDK or CloudFormation or Other Tools?
| Need | Choice |
| Plain declarative templates, no build step, tiny changes | CloudFormation YAML |
| Loops, conditions, reuse, tests, high-level patterns | CDK |
| Serverless apps with SAM CLI workflow | SAM (also a CloudFormation transform) |
| Multi-cloud IaC | Terraform |
Operations Concerns With CDK
- Pin CDK library versions and upgrade regularly. Keep the bootstrap stack current (
cdk bootstrap again after upgrades)
- Use **
RemovalPolicy.RETAIN for stateful resources. Logical IDs derive from construct IDs, so renaming a construct can replace the resource**. Check cdk diff
- Avoid hard-coded physical names. Use context for environment lookups and commit
cdk.context.json
- Test: unit tests with the
assertions module (Template.from_stack(stack).has_resource_properties(...)), snapshot tests, and cdk-nag for security rules
- Aspects can add tags, enforce encryption or fail the build for public buckets
CDK Pipelines
- CDK Pipelines builds a CodePipeline that self-mutates: when you push, the pipeline updates itself, then deploys stacks to dev, staging, prod stages with manual approval steps
- Needs bootstrap with trust for cross-account deployments (
--trust account)
- Failures appear in the pipeline stage and the underlying CloudFormation events
Troubleshooting
| Symptom | Fix |
This stack uses assets, so the toolkit stack must be deployed | Run cdk bootstrap for that account and Region |
Need to perform AWS calls for account ... but no credentials | Set profile or credentials, check AWS_PROFILE |
| Unexpected resource replacement in diff | Construct ID or physical name changed. Restore the ID or use overrideLogicalId |
| Deploy rolled back | Read CloudFormation stack events in the console, same as any stack |
| Version mismatch between CLI and library | Upgrade aws-cdk and aws-cdk-lib together |
Practice Tasks
- Initialize a CDK app, bootstrap and deploy a bucket stack
- Read the synthesized template and compare it with your code
- Rename a construct and observe the replacement in
cdk diff
- Add an Aspect that tags every resource
- Write a unit test asserting that the bucket blocks public access
Conclusion
CDK generates CloudFormation, so operations skills carry over: bootstrap once per account and Region, diff before deploy, retain stateful resources, watch for replacements caused by renames, pin versions, test and scan with assertions and cdk-nag, and deploy through CDK Pipelines.
Quick Summary: what CDK is; example; commands; tool choice; operations concerns; pipelines; troubleshooting.