How to remove a resource without deleting it during a cloudformation stack update
Going to elaborate on user3470009's answer.
The main, advertised purpose of the DeletionPolicy
is to keep a resource when a stack is deleted. It's mentioned almost as an afterthought in the AWS docs for DeletionPolicy
that it also functions during resource removal from a stack:
Note that this capability also applies to stack update operations that lead to resources being deleted from stacks. For example, if you remove the resource from the stack template, and then update the stack with the template.
So the workflow to remove a resource from a stack without deleting the actual resource is:
- Add
"DeletionPolicy" : "Retain"
to the resource declaration in your CF template - Apply changes by either saving in the UI or running
aws cloudformation
on the CLI or whatever other tool you use - Check in the UI that your resource has the correct changes. There are some gotchas about when CF doesn't update the metadata. See the docs link above
- Remove the resource from your template
- Apply changes. Watch the events log to see that it says
DELETE_SKIPPED
:
2018-10-15T15:32:32.956Z HostedZone DELETE_SKIPPED
Setting a DeletionPolicy of "Retain" will cause the bucket itself to remain after a stack update that deletes the resource.
When you remove a resource from your template, and update a stack from this template, the resources will be deleted. There is no way to avoid that.
Since your existing users will continue using the S3 bucket, I would recommend preserving the bucket in your template. Remove it when the bucket has been removed from your product completely.
If needed, you could version your template (old vs. new).
If you absolutely need to remove the bucket from your template, you may be able to use a loophole. When CloudFormation deletes a bucket, the bucket must be empty. If it's not empty, then the bucket should be preserved and removed from your stack. You could experiment and see if it works for you. If it works in testing, then you can try using it in production.