Deleting a stack on CloudFormation also removes all the provisioned resources in it. In some cases, you want some resources to be retained even after deleting its stack. The good thing is that you can do this by defining its DeletionPolicy.
This is pretty straightforward – you just need to define DeletionPolicy with Retain value and for the resources that support snapshot, (like RDS databases) you can set Snapshot as its value. With DeletionPolicy: Snapshot, a snapshot is created before a resource is deleted. This allows you to have a backup of the resource that’s been deleted from the stack.
Let’s say for example that you want to delete a deployed application. This app uses S3 for storing its object and RDS as its database, and you want to keep a copy of this resource as your reference. You may want to update its stack and add DeletionPolicy: Retain for S3 and DeletionPolicy: Snapshot for RDS before deleting it.
By default, deleting a stack will also delete its provisioned resources like the AWS::S3::Bucket that was launched using the below CloudFormation template.
This is an example of a CloudFormation stack template in YAML format:
Adding DeletionPolicy: Retain on the template will retain the provisioned resources even after deleting its stack.
DeletionPolicy: Snapshot can be added on resources that support snapshots like the following:
In this example, we have here a Volume created along with an EC2 instance. Because Snapshot is defined as its DeletionPolicy, we expect this to create a snapshot when the stack is deleted.
You can see from the Resources tab that an EC2 instance and a separate Volume was created.
We have two volumes here, volume mounted on the EC2 instance and the volume that was defined on the CloudFormation template.
After deleting its stack, the provisioned EC2 instance and volumes are deleted as well.
But because of the deletion policy defined as “DeletionPolicy: Snapshot” on the YAML file, a snapshot was created before the volume was deleted.