I have a stack which creates a three-tier application. I want to protect my stack from accidental deletion. Is there any way to protect an AWS CloudFormation stack?
Also I would like to know how, even if my stack gets deleted, how I can stop resources associated with the stack being deleted.
There are several ways to protect resources that are created by AWS CloudFormation.
Protect the Stack
AWS CloudFormation takes a template that describes desired resources and deploys it as a stack of resources. When a stack is deleted, the resources are deleted too.
Therefore, the first method is to control which users have permission to delete the stack. This can be assigned via Identity and Access Management (IAM).
Here is an example from the Controlling Access with AWS Identity and Access Management documentation:
A sample policy that denies the delete and update stack actions for the MyProductionStack:
A policy can also require use of a Multi-factor Authentication (MFA) code before performing sensitive operations, such as deleting a stack.
Protect the Resources
Resources created by CloudFormation can still be deleted/modified by any user with appropriate permission. Therefore, it is important that you protect important resources from being impacted by unauthorised users. AWS recommends granting least privilege so that users only have control over the resources they require, and no more.
CloudFormation Deletion Policy
A deletion policy defines resources that should not be deleted when a stack is deleted.
From the CloudFormation documentation:
DeletionPolicyattribute you can preserve or (in some cases) backup a resource when its stack is deleted. You specify a
DeletionPolicyattribute for each resource that you want to control. If a resource has no
DeletionPolicyattribute, AWS CloudFormation deletes the resource by default.
To keep a resource when its stack is deleted, specify
Retainfor that resource. You can use retain for any resource. For example, you can retain an Amazon S3 bucket or an Amazon EC2 instance so that you can continue to use or modify those resources after you delete their stacks.
This is normally used to keep resources after intentional stack deletion. For example, retaining an Amazon S3 bucket or an Amazon RDS database. However, it could also be used to preserve resource even a stack is accidentally deleted.