- Newest
- Most votes
- Most comments
When you remove a resource from a CloudFormation template and deploy the updated template, CloudFormation interprets this as an instruction to delete that resource. This is the default behavior - if a resource was previously managed by a stack and is no longer defined in the template, CloudFormation will delete it during the update.
To prevent this kind of accidental deletion in the future, you have several options:
-
Use DeletionPolicy attribute: For resources you want to retain even when removed from a template, add the
DeletionPolicy: Retainattribute to the resource definition. This tells CloudFormation to keep the resource even when it's removed from the template or when the stack is deleted. -
Use UpdateReplacePolicy attribute: This attribute controls what happens when a resource needs to be replaced during an update. Setting
UpdateReplacePolicy: Retainensures that the old resource is kept when replaced. -
Split your infrastructure: Keep stateful resources like databases in separate stacks from frequently changing components like Lambda functions. This isolation helps prevent unintended replacements or deletions.
-
Use explicit resource names: When creating resources like DynamoDB tables, specify an explicit name rather than letting CloudFormation generate one. This makes it easier to identify and reference resources across stacks.
For sharing resources across stacks, the recommended pattern is:
- Create the shared resources in one "foundation" stack with
DeletionPolicy: Retain - In other stacks, import these resources using CloudFormation's cross-stack references or by directly referencing them by name
Unfortunately, regarding your lost data, if the table was deleted and you've already created a new table with the same name, the original data is likely gone. DynamoDB doesn't automatically restore data when you recreate a table with the same name. If you had enabled Point-in-Time Recovery for the table, you might be able to restore from a backup. Otherwise, check if there are any automatic backups available in the AWS Backup service that might have captured your table before deletion.
For future protection, I recommend:
- Always use
DeletionPolicy: Retainfor production databases - Enable Point-in-Time Recovery for important DynamoDB tables
- Set up regular backups using AWS Backup
- Consider using the
RetainExceptOnCreateDeletionPolicy, which behaves likeRetainfor all stack operations except for the initial creation
Sources
DeletionPolicy attribute - AWS CloudFormation
UpdateReplacePolicy attribute - AWS CloudFormation
CDK Version Upgrade Causing DynamoDB Table Replacement and Unreferenced Historical Data | AWS re:Post
Enable Deletion Protection on DynamoDb Globaltables using Cloudformation YAML | AWS re:Post
Relevant content
asked 2 years ago
