Any unintentional changes to resources in production can cause huge problems. When you create a stack, all update actions are allowed on all resources. By default, anyone with stack update permissions can update all of the resources in the stack. During an update, some resources might require an interruption or be completely replaced, resulting in new physical IDs or completely new storage. You can prevent stack resources from being unintentionally updated or deleted during a stack update by using a stack policy. A stack policy is a JSON document that defines the update actions that can be performed on designated resources.
By default, setting a stack policy protects all stack resources and doesn’t allow any updates unless you specify an explicit Allow. This means that if you want to restrict only a few resources, you must explicitly allow all updates by including an Allow on the resource “*” and a Deny for specific resources.
If you have already created a stack with out any stack policy then you can apply stack policy to this stack using AWS CLI only. This can’t be done through Console.
> Create the below stack policy and save it in JSON file in S3 bucket. In this example, changes are allowed to all resources but for 3 resource types. Update – Delete & Replace are not allowed for Cognito UserPool, Cognito IdentityPool and DynamoDB Table.
{ "Statement" : [ { "Effect" : "Deny", "Principal" : "*", "Action" : ["Update:Delete","Update:Replace"], "Resource" : "*", "Condition" : { "StringEquals" : { "ResourceType" : ["AWS::Cognito::UserPool", "AWS::Cognito::IdentityPool","AWS::DynamoDB::Table"] } } }, { "Effect" : "Allow", "Principal" : "*", "Action" : "Update:*", "Resource" : "*" } ] }
If any stack change requires deletion or replacement of these resources then it will error out as below and all changes will be rolled back-
> Run this command in AWS CLI and apply the stack policy
aws cloudformation set-stack-policy --stack-name training-stack --stack-policy-url https://testbucket.s3-ap-southeast-2.amazonaws.com/setstackpolicy/stack_policy.json
Once applied, the Stack policy would look like below