Lesson 2 of 5 AWS CloudFormation

Updating Stacks Safely and Managing Drift

Creating infrastructure is easy; changing it without causing outages or data loss is where most of the risk lies. This lesson explains how CloudFormation decides whether an update interrupts or replaces a resource, and how change sets, stack policies, deletion policies, termination protection and rollback triggers protect production. It also covers recovering stuck rollbacks, detecting drift and importing existing resources.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain the update behaviours of resource properties: no interruption, some interruption and replacement.
  • Describe how change sets, stack policies, DeletionPolicy, UpdateReplacePolicy and termination protection prevent unintended changes.
  • Explain rollback triggers and how to recover a stack from UPDATE_ROLLBACK_FAILED.
  • Explain drift detection and resource import, and how each is used to bring resources under control.

Update Behaviours

When a property changes, CloudFormation updates the resource in one of three ways, documented for each property in the resource reference. Update with no interruption changes the resource in place without affecting its operation, such as changing tags. Update with some interruption changes it in place but may briefly interrupt it, such as changing an EC2 instance type, which requires a stop and start. Replacement creates a new resource with a new physical ID, updates dependent resources to reference it and then deletes the old one. Replacement of a database or a bucket means a new, empty resource, so it is the change to guard against.

Replacement also fails when the resource has a custom name, because two resources with the same name cannot exist at once. This is one reason to let CloudFormation generate names where possible.

Change Sets

A change set is a preview of the changes an update will make. Creating one compares the new template and parameters with the current stack and lists each resource that will be added, modified or removed, with a Replacement field of True, False or Conditional. Nothing changes until the change set is executed. Change sets are the standard way to review production changes, either manually or by a pipeline that creates a change set, waits for approval and executes it. A change set can also be created for a new stack, and it can include nested stacks so that changes in child stacks are shown.

Change sets show what CloudFormation intends to do, not every downstream effect. For example, a change set shows that a Lambda function's code will be modified, but not whether the new code works, so tests remain necessary.

The following diagram shows a change set between the template and the stack.

How a change set works. CloudFormation compares the new template and parameters with the current stack and lists each resource to be added, modified or removed, with a Replacement value of True, False or Conditional. Nothing changes until the change set is executed, so it can be reviewed by a person or approved in a pipeline first. A change set shows what CloudFormation intends to do, not whether new code works.
Check the Replacement column before executing a change set.

Protecting Resources

Several mechanisms protect resources from accidental deletion or replacement. They operate at different points and are often combined.

DeletionPolicy

Controls what happens to a resource when it is removed from the template or the stack is deleted. Delete is the default for most resources; Retain keeps the resource, which remains in the account outside the stack; Snapshot takes a final snapshot for resources that support it, such as RDS instances, EBS volumes and ElastiCache clusters, and then deletes the resource. RetainExceptOnCreate retains the resource except when the stack creation itself rolls back, which avoids leaving orphaned resources from failed creations.

UpdateReplacePolicy

Applies the same choices when an update replaces a resource: the old resource is retained, snapshotted or deleted. Setting both policies to Retain or Snapshot on stateful resources means that neither deletion nor replacement can destroy data without a recovery point.

Stack policy

A JSON document attached to a stack that allows or denies update actions (Update:Modify, Update:Replace, Update:Delete and Update:*) on resources, by logical ID or resource type. Once a stack policy exists, all resources are protected by default unless explicitly allowed. A stack policy applies to every update, whoever performs it, and can be overridden temporarily for one update by supplying a stack policy during the update. It does not prevent stack deletion.

Termination protection

Prevents the stack from being deleted until protection is disabled. It protects against deleting the whole stack but not against updates that remove resources.

The table below summarises what each mechanism prevents.

MechanismProtects againstScope
DeletionPolicy Retain or SnapshotData loss when a resource is removed or the stack is deletedOne resource
UpdateReplacePolicy Retain or SnapshotData loss when an update replaces a resourceOne resource
Stack policyUnintended modification, replacement or deletion during updatesResources in one stack
Termination protectionDeleting the entire stackOne stack
IAM policies and service rolesUnauthorised stack operationsPrincipals

The following diagram shows what each mechanism protects.

What each protection mechanism prevents. DeletionPolicy Retain or Snapshot protects a resource's data when it is removed from the template or the stack is deleted. UpdateReplacePolicy does the same when an update replaces the resource. A stack policy denies modification, replacement or deletion of resources during updates, whoever performs them. Termination protection prevents deletion of the whole stack. IAM policies and service roles control who can run stack operations at all.
The mechanisms protect against different events and are combined.
Sort into groups

Choose the protection

Exam skills 2.1.1 · 3.3.2

Choose the CloudFormation feature that gives each protection.

Log in to try this activity Interactive activities are free with an account.

Rollback Triggers and Rollback Failures

A stack update can complete successfully in CloudFormation's view while breaking the application. Rollback triggers address this: a stack's rollback configuration lists up to five CloudWatch alarms and a monitoring time of up to 180 minutes. During the operation and the monitoring period, if any alarm enters the ALARM state, CloudFormation rolls back the update. This gives CloudFormation-deployed changes the same alarm-based safety that CodeDeploy provides for applications.

Sometimes a rollback itself fails, leaving the stack in UPDATE_ROLLBACK_FAILED. Typical causes are a resource changed or deleted outside CloudFormation, insufficient permissions or a resource limit. The stack cannot be updated in this state. The fix is to correct the cause, for example by restoring the missing resource, and then call ContinueUpdateRollback; if a resource cannot be fixed, it can be skipped with --resources-to-skip, after which CloudFormation marks it as rolled back and the stack's view of it may need reconciling.

For faster development iterations, a stack operation can preserve successfully provisioned resources on failure (the --disable-rollback option or the console setting), so that only the failed resources need fixing before retrying.

Fill in the value

Rollback triggers

Exam skills 3.3.2 · 1.4.4

Recall the limits of CloudFormation rollback triggers.

Log in to try this activity Interactive activities are free with an account.

Drift Detection

Drift occurs when a resource is changed outside CloudFormation, for example when an administrator edits a security group in the console. Drift detection compares the actual configuration of supported resources with the template's expected configuration and reports each resource as IN_SYNC, MODIFIED, DELETED or NOT_CHECKED, with the differing properties. It checks only properties that the template sets explicitly. Drift detection can be run on demand, on stacks and on stack sets, and the AWS Config managed rule cloudformation-stack-drift-detection-check runs it continuously and reports drifted stacks as non-compliant, which can start automated notification or remediation.

Drift is resolved either by updating the template to match the intended change or by updating the stack so that CloudFormation restores the declared configuration. Preventing drift is better than detecting it: restricting console write access to production and making the pipeline the only path for changes removes most causes.

Importing Existing Resources

Resources created manually can be brought under CloudFormation management with resource import. The template is updated to declare the resource with a DeletionPolicy (required for import) and properties matching its current configuration, and an import change set identifies each resource by its identifier, such as a bucket name. After import, the resource is managed like any other. Import is also used to move resources between stacks: set DeletionPolicy: Retain, remove the resource from the first stack, and import it into the second. The CloudFormation IaC generator can scan an account and produce a template for existing resources to start this process.

Worked example

Protecting a Production Database Stack

A stack contains an Amazon RDS database, an application Auto Scaling group and security groups. A previous update accidentally replaced the database because a property that requires replacement was changed. The organisation wants to prevent recurrences and to roll back application changes that raise the error rate.

  1. Resource policies

    Set DeletionPolicy and UpdateReplacePolicy to Snapshot on the database.

  2. Stack policy

    Attach a stack policy that denies Update:Replace and Update:Delete on the database's logical ID and allows all other updates.

  3. Review

    Deploy through a change set and approval, reviewing the Replacement column.

  4. Rollback triggers

    Add the application's 5xx alarm as a rollback trigger with a 15-minute monitoring time.

  5. Deletion

    Enable termination protection on the stack.

Check yourself

A stack is in UPDATE_ROLLBACK_FAILED because a security group that the stack created was deleted manually. How is the stack recovered?

Show answer

Use ContinueUpdateRollback. If the security group cannot be recreated, skip it with resources-to-skip so the rollback can complete, then reconcile the template and resources with a later update.

Exam Tips

Remember for the exam

  • Change sets preview updates, including whether each resource will be replaced; execute them only after review.
  • Set DeletionPolicy and UpdateReplacePolicy to Retain or Snapshot on stateful resources; a stack policy denies updates such as Update:Replace on protected resources; termination protection prevents stack deletion.
  • Rollback triggers (up to five alarms, up to 180 minutes of monitoring) roll back updates that degrade the application.
  • Recover UPDATE_ROLLBACK_FAILED with ContinueUpdateRollback, skipping resources that cannot be fixed.
  • Drift detection compares explicitly set properties; use the cloudformation-stack-drift-detection-check Config rule for continuous checks.
  • Resource import requires a DeletionPolicy on the imported resource and can move resources between stacks.