Using a Deletion Policy to protect resources deployed using AWS CloudFormation


Brett Gillett

This post is part of a series of introductory articles related to building AWS services using AWS CloudFormation. You can read about CloudFormation Conditions, CloudFormation Parameters, and the DependsOn attribute in earlier posts

By default, when you delete a CloudFormation Stack, all resources are deleted (there are some exceptions - check the AWS DeletionPolicy documentation page to be sure). In most situations, this may be what you would like to happen; however, you may have business-critical resources that require an extra level of protection.

Protect resources deployed via CloudFormation by using a Deletion Policy. By adding this option, you can override CloudFormation’s default delete operation and gain more control.

Once added, a Deletion Policy controls what happens when you run a Delete (or Update) Stack operation. Remember - not all Stack Update operations cause the replacement of a resource. Therefore, when running a Stack Update operation, the Deletion Policy will only be applied to situations where the resource requires replacement.

How do you know if a resource will be replaced? The CloudFormation resource and property documentation will give you all the information you need.

Depending on the AWS resource, you can retain the resource, create a snapshot before deleting the resource, or delete the resource (default operation).

Adding a DeletionPolicy to your CloudFormation Stack couldn’t be any easier.

1
2
3
4
5
6
7
8
mysql0:
    Type: AWS::RDS::DBInstance
    DeletionPolicy: Snapshot
    Properties:
        AllocatedStorage: !Ref storage
        AllowMajorVersionUpgrade: false
        AutoMinorVersionUpgrade: true
        ...
In the above example, a final RDS DB snapshot is created by CloudFormation deletes the resource.

1
2
3
4
5
6
7
8
mysql0:
    Type: AWS::RDS::DBInstance
    DeletionPolicy: Retain
    Properties:
        AllocatedStorage: !Ref storage
        AllowMajorVersionUpgrade: false
        AutoMinorVersionUpgrade: true
        ...
In the above example, CloudFormation will retain the resource during a Delete (or Update) operation.


Brett Gillett


Orbit

Like what you read? Why not subscribe to the weekly Orbit newsletter and get content before everyone else?