AWS CloudFormation Cheat Sheet
Template syntax and CLI commands for defining and deploying AWS infrastructure as code with CloudFormation stacks.
Basic Template
Minimal template creating an S3 bucket.
AWSTemplateFormatVersion: '2010-09-09'Description: Simple S3 bucket stackParameters: BucketName: Type: StringResources: MyBucket: Type: AWS::S3::Bucket Properties: BucketName: !Ref BucketNameOutputs: BucketArn: Value: !GetAtt MyBucket.Arn
Intrinsic Functions
Common functions used inside templates.
# Reference a parameter or resource!Ref MyBucket# Get an attribute of a resource!GetAtt MyBucket.Arn# String substitution!Sub "${AWS::StackName}-bucket"# Join strings!Join ["-", ["prefix", !Ref BucketName]]# Conditional!If [IsProd, "prod-value", "dev-value"]
CLI: Deploy & Manage Stacks
Create, update, and delete stacks.
aws cloudformation deploy \ --template-file template.yaml \ --stack-name my-stack \ --parameter-overrides BucketName=my-unique-bucket \ --capabilities CAPABILITY_IAMaws cloudformation describe-stacks --stack-name my-stackaws cloudformation delete-stack --stack-name my-stackaws cloudformation validate-template --template-body file://template.yaml
Key Concepts
Key key concepts to know.
- Stack- A collection of resources managed together as a single unit
- Change Set- Preview of changes CloudFormation will make before applying an update
- Nested Stack- A stack referenced as a resource inside a parent stack for modularity
- Drift Detection- Identifies resources manually changed outside of CloudFormation
- StackSets- Deploy the same stack across multiple accounts and regions
Template Top-Level Sections
Key template top-level sections to know.
- Parameters- Input values supplied at stack creation/update time
- Mappings- Static key-value lookup tables (e.g. region to AMI ID)
- Conditions- Boolean logic controlling whether resources are created
- Resources- Required section declaring the actual AWS resources
- Outputs- Values exported for use by other stacks or displayed after deploy
Custom Resource Backed by Lambda
Extend CloudFormation to manage resources it has no native support for.
Resources: SlackNotifier: Type: Custom::SlackWebhookRegistration Properties: ServiceToken: !GetAtt NotifierFunction.Arn WebhookUrl: !Ref SlackWebhookUrl ChannelName: deploys NotifierFunction: Type: AWS::Lambda::Function Properties: Runtime: python3.12 Handler: index.handler Role: !GetAtt NotifierRole.Arn Code: ZipFile: | import cfnresponse def handler(event, context): # event['RequestType'] is Create | Update | Delete data = {"Result": "registered"} cfnresponse.send(event, context, cfnresponse.SUCCESS, data)
DeletionPolicy & UpdateReplacePolicy
Protect stateful resources from accidental deletion or replacement during stack operations.
Resources: ProdDatabase: Type: AWS::RDS::DBInstance DeletionPolicy: Snapshot # Retain | Delete | Snapshot UpdateReplacePolicy: Retain # keeps old resource if update forces replacement Properties: Engine: postgres DBInstanceClass: db.t3.medium AllocatedStorage: 100 MasterUsername: admin MasterUserPassword: !Sub '{{resolve:secretsmanager:${DbSecret}:SecretString:password}}'
Cross-Stack References (Export / Fn::ImportValue)
Share values between independently deployed stacks without nesting.
# --- network-stack.yaml ---Outputs: VpcId: Value: !Ref MyVpc Export: Name: !Sub '${AWS::StackName}-VpcId'# --- app-stack.yaml ---Resources: AppSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: VpcId: !ImportValue network-stack-VpcId GroupDescription: App tier SG# Note: a stack cannot delete/modify an export while another stack imports it —# check with: aws cloudformation list-imports --export-name network-stack-VpcId
Stack Policies & Rollback Configuration
Lock down which resources can be updated, and control automatic rollback triggers.
# Prevent updates to a specific resource (e.g. a production DB) unless explicitly overriddenaws cloudformation set-stack-policy --stack-name my-stack \ --stack-policy-body '{ "Statement": [{ "Effect": "Deny", "Action": "Update:*", "Principal": "*", "Resource": "LogicalResourceId/ProdDatabase" }] }'# Deploy with CloudWatch alarm-based rollback monitoringaws cloudformation update-stack --stack-name my-stack \ --template-body file://template.yaml \ --rollback-configuration '{ "RollbackTriggers": [{"Arn": "arn:aws:cloudwatch:us-east-1:123456789012:alarm:HighErrorRate", "Type": "AWS::CloudWatch::Alarm"}], "MonitoringTimeInMinutes": 10 }'
Always run 'aws cloudformation create-change-set' (or use 'deploy', which does this internally) before applying updates to production stacks — reviewing the change set prevents accidental resource replacement or deletion.