AWS CDK, Terraform and Git-Based Deployment Workflows
Overview
Infrastructure as code describes resources in files that are reviewed, versioned and deployed automatically. CloudFormation is the native engine, but operators meet it through other front ends too. The AWS Cloud Development Kit (CDK) lets you write infrastructure in TypeScript, Python, Java, C# or Go and synthesizes it into CloudFormation templates. Terraform is a popular third-party tool with its own state and providers. Git holds all of it so every change has an author, a review and a rollback.
CloudFormation is like a recipe card. The CDK is a kitchen assistant that writes recipe cards for you from a few instructions ("make a three-tier web app"). Terraform is a different chef with a notebook (the state file) recording what is already in the kitchen. Either way the dishes should be made from recipes in a shared binder (Git), never improvised at the stove.
SOA-C03 asks you to create and manage resources with CloudFormation and the CDK and to use and manage third-party tools such as Terraform and Git to automate deployments.
Key Concepts
- CDK app = code using constructs (L1 = raw CloudFormation, L2 = opinionated defaults, L3 = patterns).
cdk synthproduces a template;cdk deployruns it through CloudFormation, so stacks, change sets and drift still apply. cdk bootstrapcreates the CDKToolkit stack (staging S3 bucket, ECR repo, IAM roles) in each account/Region before the first deploy; missing bootstrap is a classic failure.cdk diffpreviews changes, like a change set;cdk destroydeletes the stack;cdk importand aspects/cdk-nag help adopt and validate resources.- Terraform uses providers, a state file and
plan/apply; store state in a remote backend (S3 with versioning and encryption, with locking via DynamoDB or native S3 locking). - Git workflow: feature branch -> pull request with review and
cdk diff/terraform planoutput -> merge -> pipeline deploys; the main branch is the source of truth. - CodePipeline / CodeBuild / GitHub Actions run the deployments; use OIDC federation or IAM roles instead of long-lived keys.
- Drift occurs when someone changes resources manually; CloudFormation drift detection and Terraform
planboth reveal it; fix by re-applying code, not by hand edits. - Choose the tool by team skill and estate: CDK/CloudFormation for AWS-only with native rollbacks; Terraform for multi-cloud or existing Terraform estates.
Detailed Notes
How the tools relate
| Tool | Language | State and engine | Strengths | Watch out for |
|---|---|---|---|---|
| CloudFormation | JSON/YAML | Managed service, stack state held by AWS | Native rollback, drift, StackSets, change sets | Verbose templates |
| AWS CDK | TypeScript, Python, Java, C#, Go | Compiles to CloudFormation | Loops, conditions, reusable constructs, tests | Needs bootstrap; deploy role permissions |
| Terraform | HCL | Local/remote state file | Multi-cloud, large provider ecosystem | State management, locking, manual rollback |
| SAM | YAML extension | Transforms to CloudFormation | Serverless shorthand, local testing | Serverless focus |
CDK in practice
import * as cdk from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as s3 from "aws-cdk-lib/aws-s3";
export class NetStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, "AppVpc", { maxAzs: 2, natGateways: 1 });
new s3.Bucket(this, "Logs", {
versioned: true,
encryption: s3.BucketEncryption.S3_MANAGED,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
}
}
npm install -g aws-cdk
cdk bootstrap aws://111122223333/us-east-1 # once per account/Region
cdk synth # emit cdk.out/NetStack.template.json
cdk diff # preview changes
cdk deploy --require-approval broadening # deploy; prompt on IAM/SG widening
Common CDK failures:
| Error | Meaning | Fix |
|---|---|---|
| "This stack uses assets, so the toolkit stack must be deployed" | Not bootstrapped | cdk bootstrap in that account and Region |
AccessDenied assuming deploy role | Bootstrap trust or caller identity wrong | Check CDKToolkit roles and trust policy, re-bootstrap |
| Resource replaced unexpectedly | Logical ID or immutable property changed | Review cdk diff; set explicit names carefully or use DeletionPolicy/RETAIN |
| Lookups return dummy values | Missing env on stack | Specify account and Region for context lookups |
Terraform on AWS
terraform {
required_providers { aws = { source = "hashicorp/aws", version = "~> 5.0" } }
backend "s3" {
bucket = "corp-terraform-state"
key = "network/prod.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # native S3 locking; older setups use dynamodb_table
}
}
provider "aws" { region = "us-east-1" }
resource "aws_s3_bucket" "logs" { bucket = "corp-logs-prod" }
terraform init
terraform plan -out=tfplan
terraform apply tfplan
State problems: a locked state (previous run crashed) needs terraform force-unlock; drifted resources appear in plan; never edit state by hand except with terraform state commands and import blocks. Protect the state bucket with versioning, KMS and restricted IAM because state can contain secrets.
Git-driven delivery
| Stage | Action | Control |
|---|---|---|
| Branch and commit | Change code | Signed commits, naming conventions |
| Pull request | Peer review, cdk diff or terraform plan as comment | Required reviewers, status checks |
| Merge to main | Triggers pipeline | Branch protection |
| Deploy to dev, then prod | Pipeline role assumes target account role | Manual approval before prod |
| Detect drift | Scheduled drift detection | Alert on differences |
# GitHub Actions: assume an AWS role through OIDC, no stored keys
permissions: { id-token: write, contents: read }
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::111122223333:role/GitHubDeploy
aws-region: us-east-1
- run: npx cdk deploy --require-approval never
Handling drift
aws cloudformation detect-stack-drift --stack-name net
aws cloudformation describe-stack-resource-drifts --stack-name net --stack-resource-drift-status-filters MODIFIED DELETED
Remediate by updating the code to the desired state and redeploying, or by importing resources, and prevent drift with restrictive IAM and AWS Config rules.
Real World Example
Scenario – consistent environments across accounts. A fintech wants identical dev, test and prod VPCs. Engineers write one CDK app with environment-specific parameters, stored in Git. A pull request shows cdk diff output as a comment, a reviewer approves, and CodePipeline deploys to dev, then waits for manual approval before prod.
A partner team keeps its legacy estate in Terraform with an S3 remote backend and locking. Both approaches share the same review and approval flow. A nightly job runs CloudFormation drift detection and terraform plan, and any manual console change raises an SNS alert so it is corrected through a pull request.
Architecture Diagram
- 1Engineers commit infrastructure code to a Git branch and open a pull request.
- 2The pipeline runs cdk synth/diff or terraform plan and posts the result for review.
- 3After approval and merge, the pipeline assumes a deployment role in the target account.
- 4CloudFormation (or Terraform) creates and updates resources; failures roll back or report.
- 5Scheduled drift detection and Config rules flag manual changes.
Best Practices
- ✓Bootstrap every target account and Region before CDK deployments and keep the toolkit stack current.
- ✓Use OIDC or IAM roles, never static access keys, in pipelines; scope deploy roles to least privilege.
- ✓Store Terraform state remotely with versioning, encryption and locking, and restrict access.
- ✓Review
cdk diff/terraform planoutput before every production deploy and require approvals. - ✓Detect and fix drift through code; block console edits with SCPs or IAM where possible.
Common Interview Questions
Exam Tips
SOA-C03 focus
- CDK output is CloudFormation;
cdk bootstrapfixes missing toolkit stack errors. - Preview before deploy: change sets,
cdk diff,terraform plan. - Third-party IaC state -> remote backend (S3) with locking; credentials in pipelines -> OIDC / IAM role, not keys.
- Manual changes causing differences -> drift detection.
Finished this lesson?
0 of 46 lessons done · 0% of the course

