WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Saturday, May 16, 2015

Trivial bash Script to restart services in AWS

Too many aws servers? Been there and I hate it. Following is a simple script that I use to restart services running on EC2 instances. I am using AWS Cli to get the ip address based on tag names and then ssh into the box and to the command. Note that the tag names are the same as service names in my case.
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
#!/bin/bash
 
set -e
 
function usage {
  echo >&2 "Usage: $0 [ -e environment -n service_name -a action ]"
  exit 1
}
 
while getopts ":n:e:a:" FLAG; do
  case $FLAG in   
 n) NAME=${OPTARG};;
 e) ENV=${OPTARG};;
 a) ACTION=${OPTARG};;
 [?]) usage;;
  esac
done
 
if [[ -z $NAME || -z $ENV || -z $ACTION ]]; then
  usage
fi
 
for fid in $(aws ec2 describe-instances --filters "Name=tag:ServerEnv,Values=${ENV}" "Name=tag:SubSystem,Values=${NAME}" --query 'Reservations[*].Instances[*].PrivateIpAddress' --output text)
do
 ssh -n $fid "sudo ${ACTION} ${NAME}; exit;"
done

Labels: ,