Last active
July 1, 2017 01:26
-
-
Save shadiakiki1986/a4bc2956eaaef7dede10 to your computer and use it in GitHub Desktop.
Helper for aws ec2 CLI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This is a helper for aws ec2 CLI | |
# https://gist.github.com/shadiakiki1986/a4bc2956eaaef7dede10 | |
if [ $# -ne 2 ] || [ "$2" == "help" ]; then | |
echo "Usage:" | |
echo " bash $0 id '*'" | |
echo " bash $0 id udacity" | |
echo " bash $0 id '*udacity*'" | |
echo " bash $0 start id" | |
echo " bash $0 state id" | |
echo " bash $0 ip id" | |
echo " bash $0 stop id" | |
echo " bash $0 start 'ffa-mfe test 4'" | |
echo " bash $0 stop 'ffa-mfe test 4'" | |
echo " bash $0 state 'ffa-mfe test 4'" | |
echo " bash $0 ssh 'ffa-mfe test 4'" | |
echo " bash $0 help" | |
exit 1 | |
fi | |
main() { | |
cmd="$1" | |
id="$2" | |
case "$cmd" in | |
"id") | |
aws ec2 describe-instances --filters "Name=tag-value,Values=$id" --query 'Reservations[*].Instances[*].[InstanceId,Tags[*].Value]' --output text | |
;; | |
"start") | |
aws ec2 start-instances --instance-ids "$id" | |
;; | |
"ip") | |
aws ec2 describe-instances --instance-ids "$id" --query 'Reservations[*].Instances[*].NetworkInterfaces[*].Association' --output text | |
;; | |
"stop") | |
aws ec2 stop-instances --instance-ids "$id" | |
;; | |
"state") | |
x=$(aws ec2 describe-instances --instance-ids "$id" --query 'Reservations[*].Instances[*].State' --output text) | |
if [ $? -eq 0 ]; then | |
echo $x | awk '{print $2}'; | |
else | |
return $? | |
fi | |
;; | |
esac | |
} | |
if [ "$1" != "ssh" ]; then | |
main "$1" "$2" | |
exit | |
fi | |
id1="$2" | |
echo main state "$id1" | |
state=$(main 'state' "$id1") | |
if [ $? -ne 0 ]; then | |
echo main id $id1 | |
id2=$(main "id" "$id1") | |
if [ $? -ne 0 ]; then | |
echo "Couldnt match neither ID nor name. Aborting" | |
exit 1 | |
else | |
id1=$id2 | |
echo main state $id2 | |
state=$(main "state" "$id2") | |
fi | |
fi | |
echo "State is '$state'" | |
case "$state" in | |
"*") | |
echo "State not stopped ... not doing anything" | |
exit 3 | |
;; | |
"stopped") | |
main "start" $id1 | |
echo "Sleeping 30 secs while ec2 instance boots" | |
sleep 30 | |
;; | |
"running") | |
echo "Already running, not doing anything, just ssh" | |
;; | |
esac | |
echo main ip $id1 | |
ip=$(main "ip" $id1|awk '{print $3}') | |
echo "Result: $ip" | |
if [ -z "$ip" ]; then | |
echo "ec2 instance not up after 30 secs. Aborting" | |
exit 2 | |
fi | |
ssh -i aws1.pem ubuntu@$ip |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment