Sub topic 11
Creating, updating and deleting stacks
This chapter assumes you can write a basic template (Resources, Parameters, Outputs) and have the AWS CLI configured with credentials that can call CloudFormation and create the resources in your template.
What a stack is
A stack is the unit CloudFormation manages. You give CloudFormation a template and a stack name, and it creates a stack that owns every resource the template declares. Later operations (update, delete) act on the stack as a whole. CloudFormation tracks which physical resource belongs to which logical ID in the template, so it can work out what to change.
Stack names are unique within an account and Region. They must start with a letter, and they can contain letters, numbers and hyphens.
The stack lifecycle
Every operation moves the stack through *_IN_PROGRESS states and ends in a *_COMPLETE or *_FAILED state.
The failure states are covered in detail in the chapter on rollback. For now, note one rule: a stack that fails on its first creation ends in ROLLBACK_COMPLETE. That stack cannot be updated. You can only delete it and create it again.
Creating a stack
The simplest way to create or update a stack is aws cloudformation deploy. It creates the stack if it does not exist, and otherwise updates it. Behind the scenes it builds a change set, executes it, and waits for the result.
aws cloudformation deploy \
--template-file template.yaml \
--stack-name demo \
--parameter-overrides EnvName=devdeploy blocks until the operation finishes and prints the outcome. Use it in scripts and pipelines.
The lower-level command is create-stack. It returns immediately, so you wait for completion yourself:
aws cloudformation create-stack \
--stack-name demo \
--template-body file://template.yaml \
--parameters ParameterKey=EnvName,ParameterValue=dev
aws cloudformation wait stack-create-complete --stack-name demo
aws cloudformation describe-stacks \
--stack-name demo \
--query "Stacks[0].[StackStatus,Outputs]"The wait command polls until the stack reaches CREATE_COMPLETE. It exits with a non-zero code if the stack reaches a failure state instead, which makes it safe to use in a script.
Capabilities and template size
- If your template creates IAM resources, CloudFormation makes you acknowledge it. Pass
--capabilities CAPABILITY_IAM. UseCAPABILITY_NAMED_IAMif the template sets custom IAM resource names. Without the flag, the call fails with anInsufficientCapabilitiesExceptionerror. --template-bodyaccepts a template of up to 51,200 bytes. A larger template must be uploaded to S3 and passed with--template-url. A template in S3 can be up to 1 MB.- With
deploy, add--s3-bucketto have the CLI upload the template for you.
Updating a stack
To update a stack, submit a changed template, changed parameter values, or both. CloudFormation compares the new desired state with the stack's current state. It then creates, modifies, or deletes only the resources that differ.
aws cloudformation deploy \
--template-file template.yaml \
--stack-name demo \
--parameter-overrides EnvName=prodThree behaviors matter in practice:
- Resources are matched by logical ID. If you rename a logical ID in the template, CloudFormation sees a new resource and an old one that no longer exists. It creates the new one and deletes the old one. For a stateful resource such as a bucket or database, this can destroy data.
- A changed property may replace the resource. Some properties update in place, and others force a new physical resource. The next chapter explains how to predict which one you will get.
- An update with no differences does nothing. With AWS CLI v2,
deploytreats this as a failure and exits with a non-zero code. Add--no-fail-on-empty-changesetto make it exit successfully.
CloudFormation updates only what you declared. If someone changes a resource by hand in the console, the next update does not necessarily undo that change. Drift detection, covered later, finds those differences.
Deleting a stack
aws cloudformation delete-stack --stack-name demo
aws cloudformation wait stack-delete-complete --stack-name demoCloudFormation deletes the resources in reverse dependency order. Resources that depend on others go first, so a bucket policy is removed before its bucket, for example.
Deletion fails, and the stack enters DELETE_FAILED, in these common cases:
- An S3 bucket still contains objects. Empty the bucket, then retry.
- Another stack imports one of this stack's exported values.
- A resource was changed outside CloudFormation, or its permissions were removed, so the delete call is rejected.
- Termination protection is enabled on the stack. In that case the request is rejected and the stack stays as it was.
A resource with DeletionPolicy: Retain is skipped during deletion and left running in your account. The stack goes away, but you still pay for the resource and must remove it yourself.
Watching what happened
Each operation writes events, one per resource per status change. Read them when something fails, or just to follow progress:
aws cloudformation describe-stack-events \
--stack-name demo \
--query "StackEvents[].[Timestamp,LogicalResourceId,ResourceStatus,ResourceStatusReason]" \
--output tableEvents are listed newest first. The ResourceStatusReason column holds the error message for a failed resource. The earliest failed event is usually the root cause, because later failures are often side effects of the cancelled work.
Exercise
You rename the logical ID of a bucket in your template from AppBucket to DataBucket and deploy the update. The template has no DeletionPolicy on the bucket. What does CloudFormation do, and how should you avoid data loss?
Show answer
CloudFormation matches resources by logical ID, so it creates a new bucket named for DataBucket and then deletes the old AppBucket, which loses the data if the bucket is removed. To avoid this, preview the update first, and set DeletionPolicy: Retain (and UpdateReplacePolicy: Retain) on stateful resources before changing anything. Then copy the data or import the retained bucket under the new logical ID.
Exercise
A first-time create-stack ends in ROLLBACK_COMPLETE. You fix the template and run deploy with the same stack name. What happens, and what must you do first?
Show answer
The operation is rejected, because a stack in ROLLBACK_COMPLETE cannot be updated. Delete the failed stack with delete-stack, wait for DELETE_COMPLETE, and then deploy again.