
September 09, 2026
12 min read
By Kokil Thapa | Last reviewed: September 2026
AWS CDK: Infrastructure as Real Code turns CloudFormation into something you can write in TypeScript, Python, Java, C#, or Go. You model VPCs, databases, queues, and Lambda functions as typed classes. CDK synthesizes a CloudFormation template and deploys it through the same AWS control plane Terraform and raw YAML use. If you already ship Laravel on AWS EC2 with RDS, CDK gives you a versioned, reviewable path from laptop to production without hand-clicking the console.
cdk synth to produce CloudFormation, then cdk deploy to provision stacks. Constructs encapsulate patterns; L3 constructs ship opinionated defaults you extend in code.What is AWS CDK and how is it different from CloudFormation?
CloudFormation describes infrastructure in JSON or YAML. It works, but large templates become hard to refactor. Loops, shared modules, and unit tests feel bolted on. AWS CDK sits on top of CloudFormation and adds a software development layer.
You write an app containing one or more stacks. Each stack holds constructs — reusable building blocks for S3 buckets, RDS instances, or entire web tiers. When you run synthesis, CDK emits a CloudFormation template AWS executes. Nothing bypasses CloudFormation; CDK is a compiler, not a parallel provisioner.
Construct levels you will actually use
CDK ships three construct tiers. Knowing them saves hours of confusion during your first stack.
- L1 (Cfn*) — one-to-one CloudFormation resources. Use when a new AWS feature lands before higher-level constructs exist.
- L2 — sensible defaults, helper methods, and grant APIs. Most day-to-day work lives here.
- L3 — opinionated patterns such as
ApplicationLoadBalancedFargateService. Fast to ship; harder to customize deeply.
For background on the underlying engine, read the companion piece on AWS CloudFormation as infrastructure as code. CDK does not replace CloudFormation knowledge. It makes large templates manageable.
How do you set up an AWS CDK project from scratch?
CDK requires Node.js 18 or later. For greenfield work in 2026, use Node.js 26 LTS and npm 12. Install the CLI globally, bootstrap your account once, then scaffold a project.
- Install the AWS CDK CLI:
npm install -g aws-cdk - Verify versions:
node --versionandcdk --version - Configure AWS credentials via IAM Identity Center or an access key with least privilege
- Scaffold:
cdk init app --language=typescript - Bootstrap the target account/region:
cdk bootstrap aws://ACCOUNT_ID/REGION - Synth locally:
cdk synth - Deploy:
cdk deploy
Bootstrap creates an S3 staging bucket and IAM roles CDK needs for asset uploads. Skip it once per account/region pair and deployments fail with opaque errors. I've seen teams burn an afternoon on that single missed step.
Minimal TypeScript stack
Below is a trimmed stack that provisions a private S3 bucket with encryption and blocked public access. Paste it into lib/my-stack.ts after init.
import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import { Construct } from 'constructs';
export class MyStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new s3.Bucket(this, 'AppAssets', {
encryption: s3.BucketEncryption.S3_MANAGED,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
}
}
Run cdk diff before every deploy. The diff output is your pre-flight checklist. Treat it like a pull request for infrastructure.
Official setup steps live in the AWS CDK Getting Started guide. Pin aws-cdk-lib in package.json so CI and laptops synthesize identical templates.
How do you model a production Laravel stack with AWS CDK constructs?
On client projects I often pair Laravel 12 or 13 with a classic three-tier layout: ALB, EC2 Auto Scaling, RDS MySQL 8.4 or PostgreSQL 18, ElastiCache Redis 8.10, and Secrets Manager for credentials. CDK expresses that layout as one stack or a small set of nested stacks.
Split concerns early. A networking stack exports VPC and subnet IDs. An application stack imports them and attaches compute. A data stack owns RDS and Redis. Smaller blast radius beats one monolithic template when you iterate weekly.
Example: EC2 web tier with RDS
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import * as autoscaling from 'aws-cdk-lib/aws-autoscaling';
const vpc = new ec2.Vpc(this, 'AppVpc', { maxAzs: 2 });
const db = new rds.DatabaseInstance(this, 'AppDb', {
engine: rds.DatabaseInstanceEngine.mysql({
version: rds.MysqlEngineVersion.VER_8_4,
}),
vpc,
credentials: rds.Credentials.fromGeneratedSecret('laravel'),
multiAz: true,
allocatedStorage: 50,
});
const asg = new autoscaling.AutoScalingGroup(this, 'WebAsg', {
vpc,
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.T3,
ec2.InstanceSize.MEDIUM
),
machineImage: ec2.MachineImage.latestAmazonLinux2023(),
minCapacity: 2,
maxCapacity: 6,
});
const alb = new elbv2.ApplicationLoadBalancer(this, 'Alb', { vpc, internetFacing: true });
const listener = alb.addListener('Http', { port: 80, open: true });
listener.addTargets('Web', { port: 80, targets: [asg] });
User data scripts install PHP 8.3 or 8.4, Nginx, and pull your Deployer release. For Lambda-based Laravel, swap the ASG for Laravel Vapor on AWS Lambda constructs or custom Lambda layers. The CDK pattern stays the same: encode the topology once, deploy many times.
Store database passwords in Secrets Manager, not plain environment variables. Wire rotation through CDK and reference secrets from EC2 instance roles. The dedicated guide on managing secrets with AWS Secrets Manager covers rotation details CDK can automate.
Sister legal-tech sites I maintain share a GitLab CI plus Deployer pipeline on EC2. CDK would replace hand-maintained security groups and RDS parameter groups with reviewed code. That is the practical win: fewer console edits, more audit trail.
AWS CDK vs Terraform vs Pulumi: which fits your team?
All three are infrastructure as code. CDK is AWS-native and compiles to CloudFormation. Terraform uses its own state file and HCL. Pulumi, like CDK, uses real languages but targets many clouds with one engine.
| Criterion | AWS CDK | Terraform | Pulumi |
|---|---|---|---|
| Primary target | AWS (best support) | Multi-cloud | Multi-cloud |
| Language | TypeScript, Python, Java, C#, Go | HCL (+ CDKTF optional) | TypeScript, Python, Go, .NET |
| State model | CloudFormation stacks | Remote state backend | Pulumi Service or self-hosted |
| Day-one AWS feature coverage | Fast via L1 constructs | Provider lag possible | Provider lag possible |
| Drift detection | CloudFormation drift checks | terraform plan | pulumi preview |
| Team fit | AWS-heavy TypeScript shops | Platform teams, multi-cloud | Polyglot app teams |
Pick CDK when AWS is your primary cloud and your engineers already write TypeScript or Python. Pick Terraform when you standardize one tool across AWS, GCP, and on-prem. Pick Pulumi when you want real languages without CloudFormation as the execution layer. Deeper comparisons live in Terraform infrastructure as code and Pulumi in real languages.
Reusable modules mirror Terraform's module pattern. Publish internal constructs as npm packages or Python wheels. The Terraform modules guide mindset transfers directly: one reviewed module, many consuming stacks.
How do you test and deploy AWS CDK stacks in CI/CD?
Treat CDK like application code. Synth on every pull request. Block merges when diffs introduce public S3 buckets or open security groups. Add policy-as-code with cdk-nag or CloudFormation Guard.
GitLab CI example
Many teams I work with already run GitLab CI for Laravel tests. Extend the same pipeline with a CDK job.
cdk-synth:
image: node:26
stage: test
script:
- npm ci
- npm run build
- npx cdk synth --all
artifacts:
paths:
- cdk.out/
cdk-diff:
stage: review
script:
- npx cdk diff --all
when: manual
only:
- main
Pair synth with application quality gates. Infrastructure changes deserve the same scrutiny as PHP code. Read how code coverage gates in CI keep bad merges out; apply the same discipline to cdk diff output.
For GitOps-style flows, commit synthesized templates or use CDK Pipelines for self-mutating deployment pipelines. Compare approaches in GitOps for infrastructure vs application GitOps. CDK Pipelines creates a CodePipeline that redeploys when you push to main.
Automate repetitive AWS API calls with Boto3 scripts where CDK is too heavy — one-off data migrations, for example. CDK owns steady-state topology; scripts own exceptional operations.
Context and environments
Pass context via cdk.json or -c stage=prod flags. Keep prod and staging in separate accounts when possible. AWS Organizations plus CDK environment objects make that explicit.
new MyStack(app, 'ProdStack', {
env: { account: '111111111111', region: 'ap-south-1' },
});
Nepal-based workloads often land in ap-south-1 (Mumbai) for latency to Kathmandu. Price RDS and data transfer before you commit. A quick sanity check with the Nepal EMI calculator helps founders compare monthly cloud spend against on-prem hosting quotes.
What production mistakes break AWS CDK stacks?
CDK removes YAML pain but not operational discipline. These failures show up repeatedly on real deployments.
- Skipping bootstrap — asset deployments fail until
cdk bootstrapruns in the target account/region. - Hard-coded physical names — S3 bucket names must be globally unique. Let CDK generate names unless you have a strong reason.
- Destroying stateful resources — default removal policies delete data. Set
RemovalPolicy.RETAINon RDS and S3 buckets you cannot rebuild from scratch. - Monolithic stacks — one stack with 200 resources hits CloudFormation limits and slow updates. Split by lifecycle.
- Pin drift — upgrading
aws-cdk-libwithout reading release notes changes logical IDs and replaces resources. Always runcdk diffafter upgrades. - IAM wildcards —
grantReadWritehelpers are convenient but often too broad. Tighten policies for production.
Immutable AMIs complement CDK nicely. Build golden images with Packer, reference them in your ASG construct, and stop SSH-ing into servers to patch PHP. See immutable infrastructure with Packer for the full workflow.
Governance across accounts benefits from guardrails. Tag enforcement, allowed instance types, and encryption defaults belong in policy-as-code. The overview on multi-cloud governance and policy as code applies even when you stay AWS-only.
When choosing hosting economics, weigh CDK-managed EC2 against lighter options. The comparison of AWS vs DigitalOcean vs Hetzner for Laravel helps small teams set realistic budgets — often Rs 15,000–40,000/month (~USD 110–295) for modest production tiers.
For enterprise engagements that need audited infrastructure delivery, see enterprise application development in Nepal. Ongoing stack maintenance fits support and maintenance services and Linux system administration.
Proof of shipped booking and portal workloads lives in the portfolio — for example Adventure Third Pole Trek and Mijar Law Associates. CDK would not change the Laravel code; it would codify the AWS footprint those apps run on.
Validate synthesized JSON with the JSON formatter during code review. Small syntax errors in generated templates are easier to spot when the payload is pretty-printed.
CloudFormation service limits still apply underneath CDK. The CloudFormation quotas documentation lists stack resource caps and template size limits you hit on large platforms.
Key Takeaways
- AWS CDK: Infrastructure as Real Code compiles TypeScript or Python into CloudFormation — you keep AWS-native rollback and drift tooling.
- Run
cdk bootstraponce per account/region, thencdk diffbefore every deploy to catch unintended replacements. - Split stacks by lifecycle: network, compute, and data tiers update at different speeds.
- Pair CDK with CI synth jobs, cdk-nag policy checks, and Secrets Manager for credentials — never plain-text prod secrets.
- Choose CDK for AWS-heavy teams; reach for Terraform or Pulumi when multi-cloud or non-CFN execution is the priority.
- Set
RemovalPolicy.RETAINon RDS and S3 unless you have tested backups and a written destroy procedure.
People Also Ask
Is AWS CDK free to use?
The CDK CLI and libraries are open source and free. You pay only for AWS resources your stacks create — EC2, RDS, data transfer, and the rest. Bootstrap resources (S3, ECR, IAM) carry normal AWS pricing, usually pennies at small scale.
Can AWS CDK replace Terraform entirely?
Only if AWS is your sole cloud and CloudFormation's execution model fits your operations team. Terraform still wins when one toolchain must manage AWS, GCP, Azure, and SaaS providers together. Many organizations use CDK for AWS application stacks and Terraform for shared networking.
Which language should I pick for AWS CDK?
TypeScript is the best-documented path and matches most CDK examples. Python fits data and ML teams. Java and C# suit enterprises with existing JVM or .NET standards. Pick the language your reviewers already read fluently.
Does AWS CDK work with existing CloudFormation templates?
Yes. Import templates with CfnInclude or migrate resource by resource into L2 constructs. Incremental migration beats a big-bang rewrite on production systems that already run steady traffic.
Ship infrastructure the same way you ship Laravel code
AWS CDK: Infrastructure as Real Code closes the gap between application repos and the AWS console. You get typed constructs, repeatable synth output, and CloudFormation's battle-tested deployment engine. Start with one stack — a VPC, an ALB, an RDS instance — and expand through internal construct libraries as patterns stabilize.
If you want help modeling production Laravel stacks, CI pipelines, or a migration from hand-built EC2 to codified AWS, contact us to discuss scope. Solid infrastructure code pays back every deploy night you do not spend fixing security groups by hand.
Frequently Asked Questions
0 Comments
Leave a comment
Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

