-
Notifications
You must be signed in to change notification settings - Fork 1
/
aws-create-cloudformation.sh
executable file
·58 lines (51 loc) · 1.88 KB
/
aws-create-cloudformation.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/bin/bash
# Parse arguments:
while getopts ":r:p:v" opt; do
case $opt in
r) REGION="--region $OPTARG";;
p) PROFILE="--profile $OPTARG";;
v) VERBOSE=$(( VERBOSE + 1 ));;
:) echo "Option -$OPTARG requires an argument." >&2; exit 1;;
\?) echo "Invalid option: -$OPTARG" >&2;;
esac
done
shift $((OPTIND-1))
if [[ "$2" == "" ]]; then
echo "Usage: ${0##*/} [-p profile] [-r region] [-v] stack-name template-filename"
echo " This script will create the given stack specified by the template."
exit 1
fi
Identity=$(aws $PROFILE sts get-caller-identity 2>&1)
if [[ "$Identity" =~ Unable.to.locate.credentials ]]; then
echo "Error, the given profile was not found." >&2
exit 1
fi
if [[ "$Identity" =~ An.error.occurred..ExpiredToken ]]; then
echo "Error, the given profile has expired." >&2
exit 1
fi
account=$(echo "$Identity" | jq -r '.Account')
role=$(echo "$Identity" | jq -r '.Arn | sub("arn:aws:sts::[0-9]*:assumed-role/";"") | sub("/.*"; "")')
FILE="$2"
if [[ ! "$2" =~ ^/ ]]; then FILE="./$FILE"; fi
echo "Creating cloudformation stack $1 from $FILE..."
result=$(aws $PROFILE $REGION cloudformation create-stack --stack-name "$1" --template-body file://"$FILE" 2>&1)
if [[ ! "$result" =~ StackId.*arn:aws:cloudformation: ]]; then
echo "$result" >&2
exit 1
fi
StackId=$(echo "$result" | jq -r '.StackId')
function getstatus() {
aws $PROFILE $REGION cloudformation describe-stacks --stack-name "$1" | jq -r '.Stacks[] | .StackStatus'
}
echo "Waiting for the stack to be created..."
START=$(date +%s)
while sleep 10; do
status=$(getstatus "$StackId")
if [[ "$status" != "$oldstatus" ]] ; then echo $(date +"%F %T") "$status"; oldstatus="$status"; fi
if [[ ! "$status" =~ IN_PROGRESS ]]; then break; fi
sleep 10
done
echo "Total time: $(( $(date +%s) - START ))"
echo "Final status: $status"
if [[ "$status" =~ FAILED || "$status" =~ ROLLBACK_COMPLETE$ ]]; then exit 1; fi