Definition
- Template -- a YAML or JSON document that declares AWS resources and their configuration, with sections for Resources, Parameters, Mappings, Outputs, and Conditions.
- Stack -- the running instance of a template, grouping all its resources into one unit that you create, update, and delete together.
- Change Set -- a preview mechanism that shows exactly what a Stack update will add, modify, remove, or replace before execution.
- Drift Detection -- a check that compares live resources against the template and reports any manual changes.
- StackSets -- a feature that deploys the same Stack across multiple AWS accounts and regions from one place.
- SAM (Serverless Application Model) -- a CloudFormation transform that expands concise serverless resource types into the full set of plain CloudFormation resources.
Think of a CloudFormation template as the official construction blueprint for a National Bank of India branch, and the Stack as the finished branch built from that blueprint and tracked as one unit. Parameters are the blanks you fill in per branch -- city, size, vault capacity. A Change Set is the architect showing you a marked-up drawing of what will change before any wall is touched. Drift Detection is an inspector checking whether anyone moved a wall without updating the blueprint. SAM is a shorthand notation that lets you describe a complex ATM setup in one line instead of forty.
Understanding the Concepts
What is a CloudFormation template?
A template is the YAML or JSON document you write to declare AWS resources. The Resources section is the only required section -- it declares each resource with a logical name, a type like AWS::SQS::Queue, and its properties. Parameters let callers pass values at deploy time. Mappings are static lookup tables. Conditions include or configure resources only when a test passes. Outputs publish values after the Stack is created.
AWSTemplateFormatVersion: '2010-09-09'
Description: National Bank of India Fraud Alert Queue
Parameters:
Environment:
Type: String
AllowedValues: [dev, staging, production]
Default: dev
Mappings:
QueueConfig:
dev:
RetentionPeriod: 86400
production:
RetentionPeriod: 1209600
Conditions:
IsProd: !Equals [!Ref Environment, production]
Resources:
FraudAlertQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub 'nbi-fraud-alerts-${Environment}'
MessageRetentionPeriod: !FindInMap [QueueConfig, !Ref Environment, RetentionPeriod]
VisibilityTimeout: 60
FraudAlertDLQ:
Type: AWS::SQS::Queue
Condition: IsProd
Properties:
QueueName: !Sub 'nbi-fraud-alerts-dlq-${Environment}'
Outputs:
QueueUrl:
Description: URL of the fraud alert queue
Value: !Ref FraudAlertQueue
Export:
Name: !Sub '${Environment}-FraudAlertQueueUrl'
What is a Stack?
A Stack is the running instance of a template. Everything CloudFormation creates from one template is grouped into that Stack, and the Stack is the unit you create, update, and delete. Deleting the Stack deletes all its resources unless you mark some with DeletionPolicy Retain. CloudFormation tracks the Stack's state on the server side, so there is no state file to store.
# Create a stack
aws cloudformation create-stack \
--stack-name nbi-fraud-alerts-prod \
--template-body file://fraud-alerts.yaml \
--parameters ParameterKey=Environment,ParameterValue=production
# Check stack status
aws cloudformation describe-stacks --stack-name nbi-fraud-alerts-prod
StackStatus: CREATE_COMPLETE
Outputs:
- OutputKey: QueueUrl
OutputValue: https://sqs.ap-south-1.amazonaws.com/123456789/nbi-fraud-alerts-production
How do Change Sets preview updates?
A Change Set computes what a Stack update will do before you execute it. It shows which resources will be added, modified, or removed, and critically whether a change requires replacement -- destroying and recreating a resource. For a bank, you never want to discover that renaming a database caused it to be deleted and recreated.
# Create a Change Set
aws cloudformation create-change-set \
--stack-name nbi-fraud-alerts-prod \
--template-body file://fraud-alerts-v2.yaml \
--change-set-name update-retention
# Review the Change Set
aws cloudformation describe-change-set \
--stack-name nbi-fraud-alerts-prod \
--change-set-name update-retention
Changes:
- Type: Resource
ResourceChange:
Action: Modify
LogicalResourceId: FraudAlertQueue
Replacement: False
Details:
- Target: MessageRetentionPeriod
ChangeSource: DirectModification
# Execute only after human review
aws cloudformation execute-change-set \
--stack-name nbi-fraud-alerts-prod \
--change-set-name update-retention
How does Drift Detection work?
Drift Detection answers whether anyone changed the Stack by hand outside CloudFormation. You trigger it on a Stack, and CloudFormation compares the live resources against the template's expected configuration, reporting any drifted properties.
# Start drift detection
aws cloudformation detect-stack-drift \
--stack-name nbi-fraud-alerts-prod
# Check results
aws cloudformation describe-stack-resource-drifts \
--stack-name nbi-fraud-alerts-prod
StackResourceDrifts:
- LogicalResourceId: FraudAlertQueue
StackResourceDriftStatus: MODIFIED
PropertyDifferences:
- PropertyPath: /VisibilityTimeout
ExpectedValue: "60"
ActualValue: "30"
DifferenceType: NOT_EQUAL
How do nested stacks and StackSets work?
Nested stacks break a big template into smaller reusable child templates. A parent references a child via AWS::CloudFormation::Stack. StackSets deploy the same Stack across many AWS accounts and regions from one place, which is how a large bank rolls out a standard security baseline to every account.
# parent-stack.yaml
Resources:
NetworkStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://s3.amazonaws.com/nbi-templates/networking.yaml
Parameters:
VpcCidr: '10.0.0.0/16'
DatabaseStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://s3.amazonaws.com/nbi-templates/database.yaml
Parameters:
VpcId: !GetAtt NetworkStack.Outputs.VpcId
# Deploy logging baseline to all 12 NBI accounts across 3 regions
aws cloudformation create-stack-set \
--stack-set-name nbi-logging-baseline \
--template-body file://logging-baseline.yaml \
--permission-model SERVICE_MANAGED \
--auto-deployment Enabled=true
How does SAM relate to CloudFormation?
SAM (Serverless Application Model) is not a separate tool -- it is built on top of CloudFormation. A SAM template is a CloudFormation template with a Transform line that tells CloudFormation to run the SAM macro. The macro expands concise serverless types into the larger set of plain CloudFormation resources.
# SAM template -- concise serverless definition
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
FraudCheckFunction:
Type: AWS::Serverless::Function
Properties:
Handler: com.bank.fraud.FraudCheckHandler::handleRequest
Runtime: java21
MemorySize: 512
Timeout: 30
Events:
SqsTrigger:
Type: SQS
Properties:
Queue: !GetAtt FraudAlertQueue.Arn
FraudAlertQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: nbi-fraud-alerts
The SAM macro expands AWS::Serverless::Function into the Lambda function, its IAM execution role, and the SQS event source mapping. Under the hood it is still CloudFormation, still a Stack, still Change Sets and rollback.
package com.bank.fraud;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import java.math.BigDecimal;
public class FraudCheckHandler
implements RequestHandler<SQSEvent, String> {
private static final BigDecimal THRESHOLD =
new BigDecimal("500000.00");
@Override
public String handleRequest(SQSEvent event, Context context) {
for (SQSEvent.SQSMessage msg : event.getRecords()) {
String accountId = msg.getBody();
context.getLogger().log(
"Checking fraud for account: " + accountId);
// Flag transactions above 5 lakh for review
}
return "Processed " + event.getRecords().size() + " alerts";
}
}
Processed 3 alerts
What happens when a Stack update fails?
If a create or update fails partway, CloudFormation automatically rolls the Stack back to its last good state. This is a strong safety property. You never end up with half-created infrastructure. For a bank, this means a failed database resize does not leave the system in an inconsistent state.
# Stack update fails -- CloudFormation rolls back automatically
aws cloudformation describe-stack-events --stack-name nbi-fraud-alerts-prod
ResourceStatus: UPDATE_ROLLBACK_COMPLETE
ResourceStatusReason: The following resource(s) failed to update: [FraudAlertQueue]
What are common mistakes?
The most common mistakes are not using Change Sets before updating production stacks, not checking Replacement in the Change Set output, editing resources manually in the console without updating the template, and putting all resources in one giant template instead of using nested stacks.
# WRONG -- one giant template with 200 resources
# Hard to review, slow to update, big blast radius
# CORRECT -- nested stacks for separation
Resources:
Networking:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://s3.amazonaws.com/nbi-templates/networking.yaml
Database:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://s3.amazonaws.com/nbi-templates/database.yaml
What should a senior engineer know?
A senior engineer knows that you can mix SAM serverless resources and ordinary CloudFormation resources in the same template. They know that Outputs with Export allow cross-stack references, that DeletionPolicy Retain prevents accidental data loss, and that StackSets with service-managed permissions handle multi-account rollout without manual IAM setup.
Visual Overview
CloudFormation Concepts
───────────────────────
┌──────────────────────────────────────┐
│ YAML/JSON Template │
│ ┌────────────┐ ┌──────────────┐ │
│ │ Parameters │ │ Mappings │ │
│ │ Environment │ │ dev->86400 │ │
│ │ InstanceSize│ │ prod->1209600 │ │
│ └────────────┘ └──────────────┘ │
│ ┌────────────┐ ┌──────────────┐ │
│ │ Conditions │ │ Resources │ │
│ │ IsProd? │ │ SQS Queue │ │
│ └────────────┘ │ Lambda Fn │ │
│ ┌────────────┐ └──────────────┘ │
│ │ Outputs │ │
│ │ QueueUrl │ │
│ └────────────┘ │
└──────────┬───────────────────────────┘
│
▼
┌──────────────────┐ ┌──────────────────┐
│ Change Set │───▶│ Review: Add / │
│ (preview) │ │ Modify / Replace │
└──────────┬───────┘ └──────────────────┘
│ execute
▼
┌──────────────────┐
│ Stack │ managed unit
│ ┌──────┐ ┌────┐ │
│ │ Queue │ │ DLQ│ │ on failure:
│ └──────┘ └────┘ │ automatic rollback
└──────────────────┘
SAM Transform:
┌────────────────────┐ ┌───────────────────────────┐
│ Serverless::Function│────▶│ Lambda + IAM Role + │
│ (1 block) │ │ Event Source Mapping │
└────────────────────┘ │ (3 CloudFormation blocks) │
└───────────────────────────┘
Key Takeaway
CloudFormation is AWS's native Infrastructure as Code service. You write a template with Resources declaring each AWS resource, Parameters for deploy-time values, Mappings for static lookups, Conditions for optional resources, and Outputs for published values. CloudFormation provisions everything from one template as a managed Stack, tracking state on the server side so there is no state file to manage.
Three operational concepts matter for a bank. Change Sets preview exactly what will be added, modified, or replaced before you touch anything, so you never accidentally destroy a database. Drift Detection reports resources changed by hand outside CloudFormation. And if a create or update fails partway, CloudFormation automatically rolls back to the last good state.
SAM is not a competitor to CloudFormation -- it is built on top of it. A SAM template is a CloudFormation template with a Transform line that expands concise serverless types into the full set of plain resources. Under the hood it is still a Stack with Change Sets and rollback, and you can mix SAM and ordinary resources freely.
Remember one sentence: CloudFormation turns a YAML template into a managed Stack with Change Sets for preview, automatic rollback for safety, Drift Detection for honesty, and SAM as serverless shorthand.
---