Skip to content

Instantly share code, notes, and snippets.

@dcloud9
Last active June 6, 2018 19:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcloud9/8510774f1c24e80722fa to your computer and use it in GitHub Desktop.
Save dcloud9/8510774f1c24e80722fa to your computer and use it in GitHub Desktop.
Secure your stack from accidental deletion of resources like EC2 instance. Enable and Disable stack policy during updates.
#! /bin/bash -e
#-----
# Pre-reqs: AWSCLI tool (python, pip) installed and configured. -DC 28.1.15
# v1.1: Added parameter/value checks. -DC 23.2.15
#-----
StackName=$1
Profile=$3
Creds=$HOME/.aws/credentials
[ $# -lt 3 ] && (echo "Usage: $0 <stack-name> {on|off} <profile>"; exit 1)
[ $(grep -ce "\[${Profile:-null}\]" ${Creds}) -eq 0 ] && (echo 'Profile not found. Available profiles are:'; grep "\[" ${Creds}; echo "Usage: $0 <stack-name> {on|off} <profile>"; exit 1)
function listacks
{
echo Profile ${Profile} found!
aws cloudformation list-stacks --profile ${Profile} --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE UPDATE_ROLLBACK_COMPLETE|grep StackName|awk -F'[:",]' '{print $5}'
}
[ $(listacks | grep -ce ${StackName:-null}) -eq 0 ] && (echo -e "Stack: ${StackName:-null} does NOT exist! Use any of the following stacks:" ; listacks; exit 1)
case $2 in
on|ON)
aws cloudformation set-stack-policy --profile ${Profile} --stack-name ${StackName} --stack-policy-body '{
"Statement" : [
{
"Effect" : "Allow",
"Action" : "Update:Modify",
"Principal": "*",
"Resource" : "*",
"Condition" : {
"StringEquals" : {
"ResourceType" : ["AWS::IAM::User","AWS::IAM::AccessKey","AWS::S3::BucketPolicy","AWS::EC2::EIPAssociation","AWS::EC2::Route","AWS::EC2::Instance","AWS::EC2::Volume","AWS::EC2::SecurityGroupIngress","AWS::EC2::SecurityGroup"]
}
}
}
]
}'
;;
off|OFF)
aws cloudformation set-stack-policy --profile ${Profile} --stack-name ${StackName} --stack-policy-body '{
"Statement" : [
{
"Effect" : "Allow",
"Action" : "Update:*",
"Principal": "*",
"Resource" : "*",
"Condition" : {
"StringEquals" : {
"ResourceType" : ["AWS::IAM::User","AWS::IAM::AccessKey","AWS::S3::BucketPolicy","AWS::EC2::EIPAssociation","AWS::EC2::Route","AWS::EC2::Instance","AWS::EC2::Volume","AWS::EC2::SecurityGroupIngress","AWS::EC2::SecurityGroup"]
}
}
}
]
}'
;;
*)
echo "Usage: $0 <stack-name> {on|off} <profile>"
exit 1
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment