AWS Infrastructure as Code (IaC): CloudFormation, SAM, and CDK
Composing and deploying IaC templates (for example, AWS Serverless Application Model [AWS SAM], AWS CloudFormation, AWS Cloud Development Kit [AWS CDK])
AWS Infrastructure as Code (IaC): CloudFormation, SAM, and CDK
This guide covers the core tools and strategies for composing and deploying infrastructure on AWS using modern DevOps practices. It focuses on the three primary AWS-native IaC frameworks: CloudFormation, the Serverless Application Model (SAM), and the Cloud Development Kit (CDK).
Learning Objectives
After studying this guide, you should be able to:
- Differentiate between declarative (CloudFormation/SAM) and imperative (CDK) IaC approaches.
- Compose and deploy serverless applications using AWS SAM CLI commands.
- Apply CloudFormation StackSets to manage infrastructure across multiple AWS accounts and Regions.
- Implement reusable infrastructure patterns using AWS CDK constructs and CloudFormation modules.
- Select the appropriate IaC tool based on project requirements (serverless vs. general-purpose vs. code-centric).
Key Terms & Glossary
- Infrastructure as Code (IaC): The process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.
- Declarative Programming: A style where you describe what the final state should look like (e.g., CloudFormation), leaving the "how" to the provider.
- Imperative Programming: A style where you define the specific steps to achieve a state (e.g., CDK using Python or TypeScript).
- Synthesize (CDK): The process of executing CDK code to produce a CloudFormation template.
- Transformation (SAM): A macro that expands simplified SAM syntax into standard, verbose CloudFormation resources during deployment.
- StackSet: An extension of CloudFormation stacks that allows you to create, update, or delete stacks across multiple accounts and Regions with a single operation.
- Constructs: The basic building blocks of AWS CDK apps; they represent one or more AWS resources and their configurations.
The "Big Idea"
In a DevOps environment, infrastructure is treated with the same rigor as application code. By using IaC, teams eliminate Configuration Drift—where manual changes make environments inconsistent. Whether using the shorthand of SAM for serverless, the power of programming languages in CDK, or the foundational stability of CloudFormation, the goal is repeatability, version control, and automation.
Formula / Concept Box
| Feature | AWS CloudFormation | AWS SAM | AWS CDK |
|---|---|---|---|
| Primary Language | JSON / YAML | YAML / JSON | TS, JS, Python, Java, C#, Go |
| Focus | General AWS Resources | Serverless (Lambda, API Gateway) | Software Engineering approach |
| Abstraction | Low (Resource-level) | Medium (Shorthand macros) | High (L1/L2/L3 Constructs) |
| Execution | Native AWS Service | Local CLI + CloudFormation | Local CLI + CloudFormation |
Hierarchical Outline
- I. AWS CloudFormation
- Template Components: Parameters, Resources (Mandatory), Outputs, Mappings, and Transforms.
- Lifecycle: Create -> Update -> Delete; supports Change Sets to preview impacts before execution.
- Governance: Use of StackSets for multi-account/multi-region consistency.
- II. AWS Serverless Application Model (SAM)
- Extension of CFN: Uses
AWS::Serverlessnamespace transforms. - Key Resources:
Function,Api,SimpleTable(DynamoDB). - CLI Workflow:
sam init->sam build->sam deploy.
- Extension of CFN: Uses
- III. AWS Cloud Development Kit (CDK)
- The App Structure: App -> Stack -> Construct.
- Bootstrapping: Preparing an AWS environment (S3 bucket/roles) to receive CDK deployments.
- Workflow:
cdk synth(generates CFN) ->cdk deploy.
Visual Anchors
Deployment Workflow Transition
This diagram illustrates how SAM and CDK both eventually rely on the CloudFormation engine.
Multi-Account Infrastructure (StackSets)
The following diagram represents the distribution of infrastructure from a central Administrator account to Target accounts.
Definition-Example Pairs
- Resource Transform: A directive in a template that tells CloudFormation to use a macro to process the file.
- Example: Adding
Transform: AWS::Serverless-2016-10-31allows you to useAWS::Serverless::Functioninstead of the 30+ lines required for a standard Lambda resource.
- Example: Adding
- Construct (CDK): An encapsulated piece of cloud infrastructure.
- Example: The
s3.Bucketconstruct in CDK automatically handles public access blocks and encryption settings with a single line of code, which would require multiple property definitions in raw YAML.
- Example: The
- Local Invocation: Testing code in a containerized environment locally before uploading to the cloud.
- Example: Running
sam local invoketo test a Lambda function's response to an S3 event without incurring AWS costs.
- Example: Running
Worked Examples
Scenario: Creating a Serverless API
Goal: Deploy a Lambda function triggered by an API Gateway.
Method A: AWS SAM (Declarative Shorthand)
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs18.x
Events:
ApiEvent:
Type: Api
Properties:
Path: /hello
Method: getAnalysis: SAM automatically creates the API Gateway, the Lambda permissions, and the integration mapping.
Method B: AWS CDK (Imperative Code)
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigw from 'aws-cdk-lib/aws-apigateway';
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_18_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda'),
});
new apigw.LambdaRestApi(this, 'MyApi', {
handler: fn,
});Analysis: Using TypeScript provides autocomplete, type safety, and the ability to use loops or conditionals to create multiple resources.
Checkpoint Questions
- What command is used in the SAM CLI to check if your template syntax is correct before deployment?
- In AWS CDK, what is the purpose of the
cdk bootstrapcommand? - Which AWS service allows you to centrally manage and share approved IaC templates within an organization?
- True or False: AWS SAM templates can contain standard AWS CloudFormation resource types (e.g.,
AWS::S3::Bucket).
▶Click to see answers
sam validate- It provisions resources (like an S3 bucket for assets) that CDK needs to perform deployments.
- AWS Service Catalog.
- True. SAM is a superset of CloudFormation.
Muddy Points & Cross-Refs
- SAM vs. CDK: Use SAM if your team prefers YAML/JSON and is strictly serverless. Use CDK if your team consists of developers who want to use their existing language skills and need to manage complex, non-serverless infrastructure (like VPCs and RDS).
- StackSets vs. Standard Stacks: Remember that StackSets require a specific Permission Model (Self-managed using IAM roles or Service-managed using AWS Organizations).
- Nested Stacks: Used for modularity within a single account/region, whereas StackSets are for multi-account/multi-region scale.
Comparison Tables
IaC Tool Selection Matrix
| Use Case | Best Tool | Why? |
|---|---|---|
| Quick Serverless Prototype | AWS SAM | Fast local testing and minimal boilerplate. |
| Complex Enterprise App | AWS CDK | Better abstraction and use of logic (loops/classes). |
| Multi-Account Baseline | CloudFormation StackSets | Native ability to target 100+ accounts simultaneously. |
| Legacy Resource Management | CloudFormation | No extra CLI tools needed; direct engine access. |