SkillSprout
Chapter 9 · Lesson 1
Intermediate
7 min read

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 synth produces a template; cdk deploy runs it through CloudFormation, so stacks, change sets and drift still apply.
  • cdk bootstrap creates 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 diff previews changes, like a change set; cdk destroy deletes the stack; cdk import and 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 plan output -> 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 plan both 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

ToolLanguageState and engineStrengthsWatch out for
CloudFormationJSON/YAMLManaged service, stack state held by AWSNative rollback, drift, StackSets, change setsVerbose templates
AWS CDKTypeScript, Python, Java, C#, GoCompiles to CloudFormationLoops, conditions, reusable constructs, testsNeeds bootstrap; deploy role permissions
TerraformHCLLocal/remote state fileMulti-cloud, large provider ecosystemState management, locking, manual rollback
SAMYAML extensionTransforms to CloudFormationServerless shorthand, local testingServerless focus

CDK in practice

typescript
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,
    });
  }
}
bash
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:

ErrorMeaningFix
"This stack uses assets, so the toolkit stack must be deployed"Not bootstrappedcdk bootstrap in that account and Region
AccessDenied assuming deploy roleBootstrap trust or caller identity wrongCheck CDKToolkit roles and trust policy, re-bootstrap
Resource replaced unexpectedlyLogical ID or immutable property changedReview cdk diff; set explicit names carefully or use DeletionPolicy/RETAIN
Lookups return dummy valuesMissing env on stackSpecify account and Region for context lookups

Terraform on AWS

hcl
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" }
bash
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

StageActionControl
Branch and commitChange codeSigned commits, naming conventions
Pull requestPeer review, cdk diff or terraform plan as commentRequired reviewers, status checks
Merge to mainTriggers pipelineBranch protection
Deploy to dev, then prodPipeline role assumes target account roleManual approval before prod
Detect driftScheduled drift detectionAlert on differences
yaml
# 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

bash
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

Git-driven IaC pipeline
Architecture
Delivery
Git repoCDK / Terraform
CI/CD pipelinesynth / plan
CloudFormationor Terraform apply
AWS resources
Config / drift
  1. 1Engineers commit infrastructure code to a Git branch and open a pull request.
  2. 2The pipeline runs cdk synth/diff or terraform plan and posts the result for review.
  3. 3After approval and merge, the pipeline assumes a deployment role in the target account.
  4. 4CloudFormation (or Terraform) creates and updates resources; failures roll back or report.
  5. 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 plan output 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 bootstrap fixes 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