Infrastructure as code makes environments reproducible and reviewable, and CloudFormation is AWS's native engine (also under CDK).
A CloudFormation template (YAML or JSON) declares resources; a stack is a deployed instance of it. CloudFormation works out the dependency order, creates everything, and on failure rolls back to the last good state.
Template sections: Parameters (inputs), Mappings, Conditions, Resources (the only required one: logical IDs with a Type such as AWS::SQS::Queue and Properties) and Outputs. Intrinsic functions wire it together: !Ref (a parameter, or a resource's primary identifier), !GetAtt Res.Arn, !Sub "orders-${Env}", !If, !Equals, !ImportValue for another stack's exported output.
Updates are where care is needed. Changing some properties updates a resource in place; others (like a queue's name or a DynamoDB key schema) require replacement: a new resource is created and the old one deleted, data included. Always deploy through a change set, which shows each change and whether it replaces. Protect stateful resources with DeletionPolicy: Retain or Snapshot and UpdateReplacePolicy, plus stack termination protection.
Day-two features: drift detection finds manual changes made outside CloudFormation; stack policies block updates to critical resources; nested stacks and modules reuse templates; StackSets deploy one template across many accounts and Regions. Avoid hard-coding names where you can, so stacks can be deployed side by side and replacements don't collide.
aws cloudformation deploy creates and executes a change set in one step; add --no-execute-changeset to review first.
Example
AWSTemplateFormatVersion: "2010-09-09"
Description: Orders queue with a dead-letter queue
Parameters:
Env:
Type: String
AllowedValues: [dev, prod]
Conditions:
IsProd: !Equals [!Ref Env, prod]
Resources:
DeadLetters:
Type: AWS::SQS::Queue
Orders:
Type: AWS::SQS::Queue
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
QueueName: !Sub "orders-${Env}"
MessageRetentionPeriod: !If [IsProd, 1209600, 345600]
RedrivePolicy:
deadLetterTargetArn: !GetAtt DeadLetters.Arn
maxReceiveCount: 5
Outputs:
QueueUrl:
Value: !Ref Orders
# aws cloudformation deploy --template-file queue.yaml --stack-name orders-prod --parameter-overrides Env=prodRemember
- Template = parameters + resources + outputs; stack = a deployment of it
- Failed deployments roll back automatically
- Review change sets: some property changes replace resources
- Protect data with DeletionPolicy and UpdateReplacePolicy
Watch out for
- Changing a property that forces replacement of a database or queue without noticing the 'Replacement: True' in the change set.