Skip to main content

AWS CloudFormation

Core concept: CloudFormation provisions and manages AWS infrastructure as code (YAML or JSON templates).


Template Anatomyโ€‹

AWSTemplateFormatVersion: "2010-09-09"  # Always this value
Description: "My Application Stack"

Parameters: # Input values at deploy time
Environment:
Type: String
AllowedValues: [dev, staging, prod]
Default: dev

Mappings: # Lookup tables (e.g., AMI IDs per region)
RegionMap:
us-east-1:
AMI: ami-0abcdef1234567890

Conditions: # Conditional resource creation
IsProduction: !Equals [!Ref Environment, prod]

Resources: # โ† REQUIRED โ€” at least one resource
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${Environment}-my-app-bucket"
VersioningConfiguration:
Status: Enabled

Outputs: # Values to export or display
BucketName:
Value: !Ref MyBucket
Export:
Name: !Sub "${AWS::StackName}-BucketName"

Intrinsic Functions (Exam Favorites!)โ€‹

FunctionPurposeExample
!RefReference a parameter or resource!Ref Environment
!SubString substitution!Sub "${Env}-bucket"
!GetAttGet resource attribute!GetAtt MyLambda.Arn
!FindInMapLookup value in Mappings!FindInMap [RegionMap, !Ref AWS::Region, AMI]
!IfConditional value!If [IsProduction, t3.large, t3.micro]
!SelectSelect from list!Select [0, !GetAZs '']
!SplitSplit string!Split [",", !Ref CidrBlocks]
!JoinJoin values!Join [":", [a, b, c]] โ†’ a:b:c
!ImportValueImport cross-stack export!ImportValue NetworkStack-VpcId

Change Setsโ€‹

Current Stack โ†’ Create Change Set โ†’ Review Changes โ†’ Execute Change Set โ†’ Updated Stack
  • Never execute directly in production โ€” always use change sets first
  • Shows what will be added, modified, replaced, or deleted
  • Resources marked Replacement: True will be destroyed and recreated

Stack Policiesโ€‹

{
"Statement": [{
"Effect": "Deny",
"Action": "Update:Replace",
"Principal": "*",
"Resource": "LogicalResourceId/ProductionDatabase"
}]
}

Prevents accidental updates/deletions of critical resources.


DeletionPolicyโ€‹

MyDatabase:
Type: AWS::RDS::DBInstance
DeletionPolicy: Retain # Don't delete on stack deletion
# Options: Delete (default), Retain, Snapshot
PolicyBehavior
DeleteResource is deleted when stack is deleted
RetainResource kept, stack disassociates
SnapshotTake snapshot before deleting (RDS, EBS, ElastiCache)

Nested Stacks vs Stack Setsโ€‹

FeatureNested StacksStack Sets
PurposeModular templates within one accountDeploy same stack across multiple accounts/regions
Root stackParent orchestrates childrenAdmin account deploys to target accounts
Use caseVPC template, security groups templateMulti-account deployments (org-wide)

Cross-Stack Referencesโ€‹

# Stack A โ€” exports VPC ID
Outputs:
VpcId:
Value: !Ref MyVPC
Export:
Name: NetworkStack-VpcId # Must be unique per region

# Stack B โ€” imports VPC ID
Resources:
MySubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !ImportValue NetworkStack-VpcId # Reference cross-stack

๐Ÿงช Practice Questionsโ€‹

Q1. A CloudFormation stack is being updated and a new resource needs to replace an existing resource (e.g., an RDS parameter group change). Which CloudFormation feature allows the developer to preview this impact BEFORE executing the change?

A) Stack Drift Detection
B) Change Set
C) Stack Policy
D) Rollback Configuration

โœ… Answer & Explanation

B โ€” A Change Set previews what will happen to each resource (Add/Modify/Remove/Replace) without actually making changes. Always use change sets for production updates.


Q2. A developer wants to ensure that an RDS database is NOT deleted when a CloudFormation stack is deleted (for data protection). What should they set?

A) Add a Stack Policy denying delete
B) Set DeletionPolicy: Retain on the RDS resource
C) Enable termination protection on the stack
D) Use a Condition to skip deletion

โœ… Answer & Explanation

B โ€” DeletionPolicy: Retain on the RDS resource keeps it alive even when the stack is deleted. The stack will complete deletion and disassociate from the resource.


Q3. Which intrinsic function would you use to get the ARN of a Lambda function defined in the same template?

A) !Ref MyLambdaFunction
B) !GetAtt MyLambdaFunction.Arn
C) !Sub "arn:aws:lambda::${MyLambdaFunction}"
D) !FindInMap [Functions, Lambda, Arn]

โœ… Answer & Explanation

B โ€” !GetAtt retrieves attributes of a resource. !Ref on a Lambda returns the function name (not ARN). Arn is the attribute name for the function ARN.


๐Ÿ”— Resourcesโ€‹