Some operations in CloudFormation trigger a
REPLACEMENT of resources which can have unintended and catastrophic consequences, e.g. an RDS instance being replaced (which means that the current database will be deleted by CloudFormation after a new one has been created).
While CloudFormation does support deletion policies natively which prevent the deletion of resources, there is no simple way to do this for
REPLACEMENTs as of writing this.
When using CodePipeline in combination with CloudFormation to deploy infrastructure changes in an automated Continuous Delivery manner, one should have protection from accidental deletions even more mind. This blog post shows how to use CloudFormation Stack Policies to protect critical resources from being replaced.
Let’s start with the CodePipeline (expressed as CloudFormation) piece which deploys a database stack called
db (I assume you are confident with CloudFormation and CodePipeline):
The important part is the
TemplateConfiguration parameter which tells CloudFormation to look for a configuration at this particular path in the
Source artifact. In this case
db_stack_update_policy.json looks like this:
While the first statement allows all updates to all resources in the
db stack, the second will deny operations which would result in a
REPLACEMENT of the resource with the logical id
DB in this stack.
A CloudFormation stack update of
db would fail with an error message like
Action denied by stack policy: Statement [#1] does not allow [Update:Replace] for resource [LogicalResourceId/DB].