Skip to content

Instantly share code, notes, and snippets.

@citadelgrad
Last active February 7, 2024 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citadelgrad/b2ee22499b81d60b86dcdd67d123117b to your computer and use it in GitHub Desktop.
Save citadelgrad/b2ee22499b81d60b86dcdd67d123117b to your computer and use it in GitHub Desktop.
Manage cloudformation stacks
#!/bin/bash
# Set default region (you can modify this)
AWS_REGION="us-east-1"
# Error handling function
error_exit() {
echo "Error: $1" >&2
exit 1
}
# Usage function
usage() {
echo "Usage: $0 <action> <stack_name> <template_file> [-r region]"
echo "Actions:"
echo " create Create a new CloudFormation stack."
echo " update Update an existing CloudFormation stack."
echo " delete Delete a CloudFormation stack."
exit 1
}
# Check for required arguments
if [ $# -lt 3 ]; then
usage
fi
action="$1"
stack_name="$2"
template_file="$3"
shift 3
# Optional region argument
if [ "$1" == "-r" ]; then
AWS_REGION="$2"
shift 2
fi
# Validate action
case "$action" in
create|update|delete)
;;
*)
error_exit "Invalid action. Choose from create, update, or delete."
;;
esac
# Validate stack name
if [[ ! "$stack_name" =~ ^[a-zA-Z0-9-]+$ ]]; then
error_exit "Invalid stack name. Allowed characters: alphanumeric and hyphens."
fi
# Validate template file existence
if [ ! -f "$template_file" ]; then
error_exit "Template file '$template_file' not found."
fi
# AWS CLI command based on action
aws_command=""
case "$action" in
create)
aws_command="aws cloudformation create-stack"
;;
update)
aws_command="aws cloudformation update-stack"
;;
delete)
aws_command="aws cloudformation delete-stack"
;;
esac
# Set common parameters
aws_command="$aws_command --stack-name $stack_name --template-body file://$template_file --region $AWS_REGION"
# Action-specific parameters
case "$action" in
create)
# Allow empty string for capabilities
aws_command="$aws_command --capabilities CAPABILITY_NAMED_IAM"
;;
update)
# Add rollback and change-set-name for updates
aws_command="$aws_command --capabilities CAPABILITY_NAMED_IAM --rollback-triggers Replace --change-set-name ${stack_name}-update"
;;
delete)
# No additional parameters needed
;;
esac
# Execute the AWS CLI command
echo "Executing command: $aws_command"
eval "$aws_command" || error_exit "AWS CLI command failed."
echo "Stack '$stack_name' $actioned successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment