SkillSprout
Chapter 7 · Lesson 2
Intermediate
6 min read

CloudFormation, SAM and CDK

Overview

Infrastructure as Code (IaC) describes your cloud resources in files you can review, version and redeploy. AWS CloudFormation is the underlying engine: you write a template (YAML/JSON), CloudFormation creates a stack and keeps track of each resource, handling ordering and rollbacks.

Imagine a blueprint for a building. You hand the blueprint to a contractor (CloudFormation), who builds in the right order, and if something goes wrong halfway, takes down what was built. SAM is a shorthand blueprint for serverless buildings, and CDK lets you write the blueprint using a programming language.

Developers are expected to read templates, use intrinsic functions, understand change sets and stack failures, and know how SAM and CDK relate to CloudFormation.

Key Concepts

  • A template has sections: Parameters, Mappings, Conditions, Resources (required), Outputs, Transform.
  • A stack is a deployed template; change sets preview updates; drift detection finds manual changes.
  • Intrinsic functions: Ref, Fn::GetAtt, Fn::Sub, Fn::Join, Fn::ImportValue, Fn::If, Fn::FindInMap.
  • On failure during create, CloudFormation rolls back by default; updates roll back to the previous state (UPDATE_ROLLBACK_COMPLETE).
  • DeletionPolicy (Retain, Snapshot, Delete) and UpdateReplacePolicy protect stateful resources.
  • SAM is a CloudFormation transform (AWS::Serverless-2016-10-31) with CLI commands: sam init, build, local invoke, deploy, sync, logs.
  • CDK synthesises CloudFormation from TypeScript, Python, Java, C# or Go; cdk bootstrap, cdk synth, cdk diff, cdk deploy.
  • Nested stacks and StackSets (multi-account/Region) manage large or distributed infrastructure; cross-stack references use Export/ImportValue.

Detailed Notes

A CloudFormation template

yaml
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  Env:
    Type: String
    AllowedValues: [dev, prod]
    Default: dev
Conditions:
  IsProd: !Equals [!Ref Env, prod]
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    Properties:
      BucketName: !Sub "myapp-${Env}-${AWS::AccountId}"
      VersioningConfiguration:
        Status: !If [IsProd, Enabled, Suspended]
Outputs:
  BucketArn:
    Value: !GetAtt Bucket.Arn
    Export:
      Name: !Sub "${AWS::StackName}-BucketArn"
FunctionPurpose
!RefParameter value, or resource's primary ID
!GetAttResource attribute such as ARN
!SubString substitution with ${Var}
!ImportValueUse another stack's export
!If / !EqualsConditions

Use DependsOn only for implicit dependencies that Ref/GetAtt cannot express. Custom resources (Lambda-backed) run arbitrary code during stack operations, and CreationPolicy / WaitCondition wait for signals (for example cfn-signal from EC2).

Deploying with the CLI

bash
aws cloudformation deploy --template-file template.yaml \
  --stack-name myapp-dev --parameter-overrides Env=dev \
  --capabilities CAPABILITY_IAM

aws cloudformation create-change-set --stack-name myapp-dev \
  --change-set-name review --template-body file://template.yaml
aws cloudformation describe-stack-events --stack-name myapp-dev
aws cloudformation detect-stack-drift --stack-name myapp-dev

Templates that create IAM resources need CAPABILITY_IAM or CAPABILITY_NAMED_IAM. SAM and macros need CAPABILITY_AUTO_EXPAND. Some updates cause replacement (new physical resource), so review change sets.

SAM workflow

bash
sam init
sam build
sam local invoke HelloFn -e events/event.json
sam local start-api
sam deploy --guided
sam sync --stack-name myapp-dev --watch   # fast dev iteration
sam logs -n HelloFn --stack-name myapp-dev --tail
yaml
Transform: AWS::Serverless-2016-10-31
Globals:
  Function:
    Runtime: python3.12
    Timeout: 10
Resources:
  HelloFn:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      CodeUri: src/
      Events:
        Api:
          Type: Api
          Properties: { Path: /hello, Method: get }

SAM resource types: Function, Api, HttpApi, SimpleTable, LayerVersion, StateMachine, Application. SAM expands each into several CloudFormation resources (role, permission, API).

CDK in Python

python
from aws_cdk import Stack, Duration, aws_lambda as _lambda, aws_dynamodb as ddb
from constructs import Construct

class AppStack(Stack):
    def __init__(self, scope: Construct, id: str, **kw):
        super().__init__(scope, id, **kw)
        table = ddb.Table(self, "Orders",
            partition_key=ddb.Attribute(name="pk", type=ddb.AttributeType.STRING),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST)
        fn = _lambda.Function(self, "Fn", runtime=_lambda.Runtime.PYTHON_3_12,
            handler="app.handler", code=_lambda.Code.from_asset("src"),
            timeout=Duration.seconds(10), environment={"TABLE": table.table_name})
        table.grant_read_write_data(fn)   # generates least-privilege IAM

CDK has L1 (raw CFN), L2 (opinionated, grant helpers) and L3 (patterns) constructs.

Comparison

CloudFormationSAMCDK
LanguageYAML/JSONYAML (CFN extension)Programming languages
FocusAll resourcesServerlessAll resources
OutputTemplateTemplateSynthesised template
Local testingNosam localVia SAM integration

Failure handling

  • ROLLBACK_COMPLETE after failed create: the stack must be deleted before recreating.
  • UPDATE_ROLLBACK_FAILED: use ContinueUpdateRollback skipping stuck resources.
  • Stack deletion fails for non-empty S3 buckets; empty them first or use a custom resource.

Intrinsic functions and references

FunctionUse
!RefParameter value or resource ID/ARN (depends on type)
!GetAtt Res.AttrAn attribute such as Arn
!SubString substitution with ${Param} and ${AWS::Region}
!Join, !Select, !SplitString and list handling
!If, !Equals with ConditionsOptional resources per environment
!ImportValueRead another stack's exported output
Fn::Transform / TransformMacros and the SAM transform
yaml
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Parameters:
  Stage: { Type: String, Default: dev }
Conditions:
  IsProd: !Equals [!Ref Stage, prod]
Resources:
  Table:
    Type: AWS::DynamoDB::Table
    DeletionPolicy: Retain
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions: [{ AttributeName: pk, AttributeType: S }]
      KeySchema: [{ AttributeName: pk, KeyType: HASH }]
  Fn:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: python3.12
      AutoPublishAlias: live
      Environment: { Variables: { TABLE: !Ref Table } }
      Policies: [DynamoDBCrudPolicy: { TableName: !Ref Table }]
      ReservedConcurrentExecutions: !If [IsProd, 100, !Ref AWS::NoValue]
      Events:
        Api: { Type: Api, Properties: { Path: /items, Method: get } }
Outputs:
  ApiUrl:
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
    Export: { Name: !Sub "${AWS::StackName}-ApiUrl" }

SAM and CDK workflow

SAM expands AWS::Serverless::* resources into plain CloudFormation. The core commands are sam init, sam build, sam validate, sam deploy --guided (stores answers in samconfig.toml), sam sync and sam delete. The AWS CDK lets you define the same infrastructure in TypeScript or Python; cdk synth produces a template, cdk diff previews changes, cdk deploy runs CloudFormation and cdk bootstrap prepares the account with an assets bucket and roles.

typescript
const fn = new lambda.Function(this, "Fn", {
  runtime: lambda.Runtime.PYTHON_3_12, handler: "app.handler",
  code: lambda.Code.fromAsset("src"),
});
table.grantReadWriteData(fn);   // generates the least-privilege IAM policy

Use nested stacks or cross-stack exports to split large templates, StackSets for multi-account rollout, and cloudformation package or sam package to upload local code to S3 before deployment.

Real World Example

A product team manages dev, test and prod environments from one SAM template with a Stage parameter and Conditions. The pipeline runs aws cloudformation create-change-set for prod and a reviewer inspects it; a one-line change to a DynamoDB table name would have triggered replacement and data loss, which the change set exposed. They added DeletionPolicy: Retain and UpdateReplacePolicy: Retain, and use drift detection weekly to catch console edits.

Architecture Diagram

Template to stack
Architecture
Infrastructure as Code
SAM / CDK code
Template
Stack
Lambda
Table

SAM and CDK produce CloudFormation templates; CloudFormation provisions and tracks resources.

  1. 1Developers write SAM or CDK code and commit it.
  2. 2The tool produces a CloudFormation template (transform or synth).
  3. 3CloudFormation previews and applies changes in dependency order.
  4. 4On error it rolls back to the previous good state.

Best Practices

  • ✓Review change sets before updating production stacks.
  • ✓Protect stateful resources with DeletionPolicy and UpdateReplacePolicy.
  • ✓Never hard-code names or secrets; use parameters, SSM and dynamic references.
  • ✓Run drift detection and prohibit console changes.
  • ✓Use sam sync / cdk watch for rapid dev loops and pipelines for production.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Serverless IaC with local testing -> SAM; programmatic IaC -> CDK.
  • Stack stuck in ROLLBACK_COMPLETE after create -> delete and recreate.
  • IAM resources in a template require CAPABILITY_IAM.
  • Detect manual changes -> drift detection; preview changes -> change sets.

Finished this lesson?

0 of 46 lessons done · 0% of the course