TExcelTAD
Home › AWS Cloud › CloudFormation and CDK

CloudFormation and CDK

Clicking resources together in the console is fine for learning, but it is slow, error-prone and impossible to repeat exactly. Infrastructure as code (IaC) describes your infrastructure in files that you version, review and deploy like application code.

AWS CloudFormation is AWS's native IaC service. You write a template (YAML or JSON) that declares resources; CloudFormation creates them as a stack, works out the order from dependencies, and rolls back if something fails. AWS CDK (Cloud Development Kit) lets you write the same thing in TypeScript, Python, Java, C# or Go, and generates CloudFormation templates for you.

A template

yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: A versioned, encrypted bucket and a queue
Parameters:
  Env:
    Type: String
    AllowedValues: [dev, prod]
    Default: dev
Conditions:
  IsProd: !Equals [!Ref Env, prod]
Resources:
  ReportsBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "tad-reports-${Env}-${AWS::AccountId}"
      VersioningConfiguration:
        Status: !If [IsProd, Enabled, Suspended]
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault: { SSEAlgorithm: aws:kms }
  ReportsQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "reports-${Env}"
  NotifyPolicy:
    Type: AWS::SQS::QueuePolicy
    Properties:
      Queues: [!Ref ReportsQueue]
      PolicyDocument:
        Statement:
          - Effect: Allow
            Principal: { Service: s3.amazonaws.com }
            Action: sqs:SendMessage
            Resource: !GetAtt ReportsQueue.Arn
            Condition: { ArnLike: { "aws:SourceArn": !GetAtt ReportsBucket.Arn } }
Outputs:
  BucketName:
    Value: !Ref ReportsBucket
Section Purpose
Parameters Inputs at deploy time
Mappings, Conditions Lookup tables and if/else logic
Resources The only required section: what to create
Outputs Values to show or export to other stacks
Intrinsic functions !Ref, !GetAtt, !Sub, !If, !Join, !Select...
bash
aws cloudformation deploy --stack-name reports-prod --template-file reports.yaml \
    --parameter-overrides Env=prod
aws cloudformation describe-stacks --stack-name reports-prod --query "Stacks[0].[StackStatus,Outputs]"

Sample output:

text
[
    "CREATE_COMPLETE",
    [
        {"OutputKey": "BucketName", "OutputValue": "tad-reports-prod-123456789012"}
    ]
]

Model: dependency order

CloudFormation reads !Ref and !GetAtt to build a dependency graph, then creates resources in a valid order (in parallel where possible) and deletes them in reverse. A topological sort shows the idea:

python · try it yourself
from graphlib import TopologicalSorter

depends_on = {
    "ReportsBucket": set(),
    "ReportsQueue": set(),
    "NotifyPolicy": {"ReportsQueue", "ReportsBucket"},
    "AppRole": {"ReportsBucket"},
    "AppFunction": {"AppRole", "ReportsQueue"},
}

ts = TopologicalSorter(depends_on)
ts.prepare()
wave = 1
order = []
while ts.is_active():
    ready = sorted(ts.get_ready())
    print(f"wave {wave}: create {ready} in parallel")
    order += ready
    ts.done(*ready)
    wave += 1
print("delete order:", list(reversed(order)))
wave 1: create ['ReportsBucket', 'ReportsQueue'] in parallel
wave 2: create ['AppRole', 'NotifyPolicy'] in parallel
wave 3: create ['AppFunction'] in parallel
delete order: ['AppFunction', 'NotifyPolicy', 'AppRole', 'ReportsQueue', 'ReportsBucket']

Model: change sets

Before updating a stack, a change set previews what will happen. Some property changes update in place, others force a replacement (a new resource, a new physical ID, possibly data loss). Renaming an S3 bucket, for example, replaces it:

python · try it yourself
REPLACEMENT_PROPS = {"AWS::S3::Bucket": {"BucketName"}, "AWS::SQS::Queue": {"QueueName", "FifoQueue"}}

current = {
    "ReportsBucket": ("AWS::S3::Bucket", {"BucketName": "tad-reports-prod", "Versioning": "Enabled"}),
    "ReportsQueue": ("AWS::SQS::Queue", {"QueueName": "reports-prod", "VisibilityTimeout": 30}),
    "OldTopic": ("AWS::SNS::Topic", {"TopicName": "legacy"}),
}
desired = {
    "ReportsBucket": ("AWS::S3::Bucket", {"BucketName": "tad-reports-prod-v2", "Versioning": "Enabled"}),
    "ReportsQueue": ("AWS::SQS::Queue", {"QueueName": "reports-prod", "VisibilityTimeout": 120}),
    "AlertsTopic": ("AWS::SNS::Topic", {"TopicName": "alerts"}),
}

for name in sorted(set(current) | set(desired)):
    if name not in current:
        print(f"Add     {name}")
    elif name not in desired:
        print(f"Remove  {name}")
    else:
        rtype, old = current[name]
        _, new = desired[name]
        changed = sorted(k for k in set(old) | set(new) if old.get(k) != new.get(k))
        if changed:
            replace = any(k in REPLACEMENT_PROPS.get(rtype, set()) for k in changed)
            print(f"Modify  {name:<14} {changed}  Replacement: {'True' if replace else 'False'}")
Add     AlertsTopic
Remove  OldTopic
Modify  ReportsBucket  ['BucketName']  Replacement: True
Modify  ReportsQueue   ['VisibilityTimeout']  Replacement: False

Always review change sets for Replacement: True on stateful resources (databases, buckets). A DeletionPolicy: Retain or Snapshot protects data if a resource is removed from the template.

AWS CDK

With CDK you write normal code, and constructs encapsulate best practices. cdk synth produces the CloudFormation template; cdk deploy deploys it.

python
from aws_cdk import App, Stack, Duration, aws_s3 as s3, aws_sqs as sqs, aws_s3_notifications as s3n
from constructs import Construct

class ReportsStack(Stack):
    def __init__(self, scope: Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)
        bucket = s3.Bucket(self, "Reports", versioned=True, encryption=s3.BucketEncryption.KMS_MANAGED)
        queue = sqs.Queue(self, "ReportsQueue", visibility_timeout=Duration.seconds(120))
        bucket.add_event_notification(s3.EventType.OBJECT_CREATED, s3n.SqsDestination(queue))

app = App()
ReportsStack(app, "reports-prod")
app.synth()

The add_event_notification line generates the queue policy from the YAML template above automatically. Other IaC tools you will meet: Terraform/OpenTofu (multi-cloud), AWS SAM (a CloudFormation extension for serverless apps) and Pulumi.

Drift

If someone changes a stack's resource by hand, the real configuration drifts from the template. aws cloudformation detect-stack-drift finds such changes; the fix is to change the template, not the resource.

Test yourself

Which section of a CloudFormation template is required?

  1. Parameters
  2. Outputs
  3. Resources
  4. Mappings

What does a change set do?

  1. Deploys immediately
  2. Previews the changes an update would make, including replacements
  3. Deletes the stack
  4. Detects drift

What does cdk synth produce?

  1. A Docker image
  2. A CloudFormation template
  3. A Terraform plan
  4. An AMI