BrainyBeeBrainyBee
ExploreBlogStart Studying
HomeAWS Certified DevOps Engineer - Professional (DOP-C02)AWS Infrastructure as Code (IaC): CloudFormation, SAM, and CDK
Study Guide920 words

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

FeatureAWS CloudFormationAWS SAMAWS CDK
Primary LanguageJSON / YAMLYAML / JSONTS, JS, Python, Java, C#, Go
FocusGeneral AWS ResourcesServerless (Lambda, API Gateway)Software Engineering approach
AbstractionLow (Resource-level)Medium (Shorthand macros)High (L1/L2/L3 Constructs)
ExecutionNative AWS ServiceLocal CLI + CloudFormationLocal 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::Serverless namespace transforms.
    • Key Resources: Function, Api, SimpleTable (DynamoDB).
    • CLI Workflow: sam init -> sam build -> sam deploy.
  • 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.

Loading Diagram...
Figure 1 — Mermaid diagram

Multi-Account Infrastructure (StackSets)

The following diagram represents the distribution of infrastructure from a central Administrator account to Target accounts.

Compiling TikZ diagram…
⏳
Running TeX engine…
This may take a few seconds
Figure 2 — TikZ diagram

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-31 allows you to use AWS::Serverless::Function instead of the 30+ lines required for a standard Lambda resource.
  • Construct (CDK): An encapsulated piece of cloud infrastructure.
    • Example: The s3.Bucket construct 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.
  • Local Invocation: Testing code in a containerized environment locally before uploading to the cloud.
    • Example: Running sam local invoke to test a Lambda function's response to an S3 event without incurring AWS costs.

Worked Examples

Scenario: Creating a Serverless API

Goal: Deploy a Lambda function triggered by an API Gateway.

Method A: AWS SAM (Declarative Shorthand)

yaml
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: get

Analysis: SAM automatically creates the API Gateway, the Lambda permissions, and the integration mapping.

Method B: AWS CDK (Imperative Code)

typescript
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

  1. What command is used in the SAM CLI to check if your template syntax is correct before deployment?
  2. In AWS CDK, what is the purpose of the cdk bootstrap command?
  3. Which AWS service allows you to centrally manage and share approved IaC templates within an organization?
  4. True or False: AWS SAM templates can contain standard AWS CloudFormation resource types (e.g., AWS::S3::Bucket).
▶Click to see answers
  1. sam validate
  2. It provisions resources (like an S3 bucket for assets) that CDK needs to perform deployments.
  3. AWS Service Catalog.
  4. 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 CaseBest ToolWhy?
Quick Serverless PrototypeAWS SAMFast local testing and minimal boilerplate.
Complex Enterprise AppAWS CDKBetter abstraction and use of logic (loops/classes).
Multi-Account BaselineCloudFormation StackSetsNative ability to target 100+ accounts simultaneously.
Legacy Resource ManagementCloudFormationNo extra CLI tools needed; direct engine access.
All AWS Certified DevOps Engineer - Professional (DOP-C02) Study Resources

Related Notes

  • Mastering AWS Alerting and Automated Remediation1,050 words
  • Study Guide: Analyzing Failed Deployments in AWS940 words
  • Incident Analysis: Troubleshooting Failed Processes in AWS1,050 words
  • Mastering AWS Monitoring & Security Analytics: Logs, Metrics, and Findings1,050 words
  • AWS Log Analysis: Athena, CloudWatch Insights, and OpenSearch920 words
  • Analyzing Real-Time Log Streams with Amazon Kinesis Data Streams985 words
  • CloudWatch Anomaly Detection Alarms: Professional Study Guide820 words
  • AWS Application Storage Patterns: EBS, EFS, and S31,054 words
  • Lab: Automating Security Controls and Data Protection with AWS Secrets Manager and Config942 words
  • Master Study Guide: Automating Security Controls & Data Protection (AWS DOP-C02)1,184 words
  • Mastering AWS CloudFormation StackSets: Multi-Account & Multi-Region Orchestration895 words
  • Mastering System Configuration Changes in AWS945 words

Ready to study AWS Certified DevOps Engineer - Professional (DOP-C02)?

Practice tests, flashcards, and all study notes — free, no sign-up.

Start Studying

Ready to study AWS Certified DevOps Engineer - Professional (DOP-C02)?

Practice tests, flashcards, and all study notes — free, no sign-up needed.

Start Studying — Free
AWS Certified DevOps Engineer - Professional (DOP-C02) ResourcesExplore All HivesBlogHome

© 2026 BrainyBee. Free AI-powered exam prep.

Loading Diagram...
Flowchart, left to right. CDK Code (TS/Python) connects to CloudFormation Template (cdk synth). SAM Template (YAML) connects to B (Transform). B connects to CloudFormation Engine. D connects to AWS Resources. D connects to StackSets (Multi-Acct).