Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- set -ef -o pipefail
- readonly dir=$(cd "$(dirname "$0")" && pwd)
- readonly json="$dir"/tmp.json
- dryrun=false
- if [[ -f "$1" ]]; then
- file=$1
- stack_name=$(echo $file | sed s/.py//)
- else
- echo "Could not find file '$1'"; exit 1
- fi
- function help(){
- cat <<- EOF
- Usage:
- cfn_run.sh [OPTIONS] TEMPLATE_FILE
- Options:
- # -n dry-run
- -h help
- Examples:
- run:
- run.sh stack.py
- EOF
- exit 0
- }
- function message(){
- echo 🍣 "$1"
- }
- function remove_local_json(){
- message "removing local temporary file"
- rm "$1"
- }
- function confirm_prompt(){
- echo
- message "execute? (Y/n): "
- read answer
- case $answer in
- y|Y|yes)
- echo -e "tyeped yes.\n"
- return 0
- ;;
- n|N|no)
- echo -e "tyeped no.\n"
- remove_local_json $json
- return 1
- ;;
- *)
- echo -e "cannot understand $answer.\n"
- confirm_prompt
- ;;
- esac
- }
- function update_stack(){
- message "creating change-set"
- readonly change_set=$(
- aws cloudformation create-change-set \
- --change-set-name "$stack_name"-$(date "+%Y%m%d%H%M%S") \
- --stack-name "$stack_name" --template-body file://"$json")
- echo "$change_set" | jq
- readonly change_set_arn=$(echo $change_set | jq -r '.Id')
- message "describe change-set"
- aws cloudformation describe-change-set --change-set-name "$change_set_arn" | jq
- confirm_prompt
- message "execute change-set"
- remove_local_json $json
- }
- function create_stack(){
- message "creation preview"
- cat $json | jq
- confirm_prompt
- message "create stack"
- aws cloudformation create-stack --stack-name "$stack_name" --template-body file://"$json"
- remove_local_json $json
- }
- while getopts r:o:u:nh opt; do
- case "$opt" in
- n) dryrun=true;;
- h) help;;
- \?) exit 1;;
- esac
- done
- shift $((--OPTIND))
- message "flake8 linting"
- flake8 $file
- message "converting json"
- python $file > "$json"
- message "checking json syntax"
- aws cloudformation validate-template --template-body file://"$json" | jq
- message "fetch list"
- readonly stacks=($(aws cloudformation list-stacks \
- --query 'StackSummaries[?StackStatus!=`DELETE_COMPLETE`]' \
- | jq -r '.[].StackName'))
- echo ${stacks[@]}
- stack_exists=false
- for stack in "${stacks[@]}"; do
- [[ "$stack" == "$stack_name" ]] && stack_exists=true
- done
- if "$stack_exists"; then
- update_stack
- else
- create_stack
- fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement