Sub topic 24
Designing templates and stacks that last
This chapter assumes you can write a template with Parameters, Resources and Outputs. It also assumes you have created, updated and deleted stacks from the AWS CLI and have read about change sets, DeletionPolicy, drift detection, exports and nested stacks. Here you combine those features into habits that keep a stack safe to change years after you wrote it.
Split stacks by how often they change
A stack is the unit of update, rollback and deletion. Everything in one stack shares one failure and one blast radius. Group resources by lifecycle and ownership, not by service.
- Foundation: VPCs, subnets, and shared IAM roles. These change rarely and many teams depend on them.
- Stateful: databases, buckets, and queues holding data. These change rarely and must never be replaced by accident.
- Application: compute, load balancers, and functions. These change with every release.
A frequent deploy then cannot touch the database, and a failed application update rolls back without affecting the network.
Choose the sharing mechanism deliberately
| Need | Use | Main cost |
|---|---|---|
| Separate stacks owned by different teams or lifecycles | Exports and `Fn::ImportValue` | An exported value cannot change or be deleted while any stack imports it |
| One deployable unit built from reusable parts | Nested stacks | Updates go through the parent, and the whole tree rolls back together |
| Same template in many accounts or Regions | StackSets | Deployment is a separate operation with its own failure handling |
| Repeated boilerplate in templates | Transforms | Debugging happens on the expanded template |
| Logic CloudFormation cannot express | Custom resources | You own the Lambda code and its failure modes |
Exports create hard coupling. If you may need to change a shared value, pass it as a parameter, or read it from an SSM parameter that your network stack writes. Either way the consumer is not locked.
Make parameters hard to misuse
Constrain every parameter so a bad value fails before any resource is touched. Prefer typed and SSM-backed parameters over pasted IDs.
AWSTemplateFormatVersion: "2010-09-09"
Description: Instance with validated inputs and no hard-coded AMI
Parameters:
EnvName:
Type: String
Default: dev
AllowedValues:
- dev
- prod
InstanceType:
Type: String
Default: t3.micro
AllowedPattern: "^t3\\.(micro|small|medium)$"
ConstraintDescription: Must be t3.micro, t3.small or t3.medium
ImageId:
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
Resources:
AppInstance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
ImageId: !Ref ImageId
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-${EnvName}"
- Key: Environment
Value: !Ref EnvNameThe AWS::SSM::Parameter::Value<AWS::EC2::Image::Id> type resolves the latest AMI when the stack is created or updated. The same template therefore works in any Region without a Mapping of AMI IDs.
Avoid hard-coded names
Setting BucketName or TableName explicitly has two costs. The name must be unique, so you cannot deploy the template twice in one account or Region. A change that needs replacement also fails, because the new resource cannot use the name the old one still holds. Leave names out so CloudFormation generates them, and use Fn::Sub with ${AWS::StackName} in tags when you need something readable.
Protect what cannot be recreated
Set both policies on every stateful resource, because they cover different events. DeletionPolicy covers stack deletion. UpdateReplacePolicy covers replacement during an update.
Resources:
OrdersTable:
Type: AWS::DynamoDB::Table
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: OrderId
AttributeType: S
KeySchema:
- AttributeName: OrderId
KeyType: HASHAdd termination protection to the stack itself, and use a stack policy where only a few resources are allowed to change.
aws cloudformation update-termination-protection \
--stack-name demo \
--enable-termination-protectionBuild a review habit around changes
- Run
cfn-linton the template to catch invalid properties and bad references before deployment. - Run
aws cloudformation validate-templatefor a basic syntax check. - Create a change set and read it. Treat any
Replacement: Trueon a stateful resource as a stop sign. - Execute the change set only after review. Deploy to a
devstack from the same template beforeprod. - Run drift detection on a schedule, and fix the template or the resource so they agree again.
pip install cfn-lint
cfn-lint template.yaml
aws cloudformation validate-template --template-body file://template.yamlKeep templates in version control and deploy only from there. Console edits create drift, and drift makes the next update unpredictable.
Keep templates small enough to reason about
A template can hold 500 resources, but a stack near that limit is slow to update and hard to review. Split before you reach it. Use Fn::If sparingly. A template full of conditions is really two templates, and separate templates or parameterized nested stacks are easier to read. Put the Description and parameter Description fields to work, since they are the documentation people see in the console.
Exercise
A team keeps a database and its application servers in one stack. A routine instance-type change triggers an update, and a typo in a database property makes the update fail. What two design changes would reduce the risk, and what would you check before running the next update?
Show answer
Move the database into its own stack and set DeletionPolicy and UpdateReplacePolicy to Retain on it, so application updates cannot touch or roll back the database. Share the connection details with a parameter or an export. Before the next update, create a change set and confirm that no stateful resource shows Replacement: True.
Exercise
Why is a hard-coded S3 bucket name a problem for updates, not only for deploying the template twice?
Show answer
If a property change requires replacement, CloudFormation creates the new bucket before deleting the old one. The new bucket cannot take the fixed name while the old one still exists, so the update fails. A generated name avoids this.