I want a script which will restart the defined services on their respective servers. I want to pass parameter as below to the script:
eg:
sh execute.sh
Enter your server and service list: [server1:nginx,mysql],[server2:mysql,apache],[server3:mongodb,apache]
By this input the script should verify and start the services on the respective servers. I am able to do this on a single server by declaring variables.
#!/bin/bash
Instance_Name=server1
Service_Name=(nginx php-fpm mysql)
SSH_USER=admin
SSH_IDENT_FILE=~/credentials/user.pem
len=${#Service_Name[*]}
i=0
while [ $i -lt $len ]; do
service=${Service_Name[$i]}
ssh -i $SSH_IDENT_FILE -o StrictHostKeyChecking=no $SSH_USER@$Instance_Name 'service $service restart'
done
Now I don't have an idea to move forward. Please let me know if my question is unclear. Thanks in advance.
Parse your input parameters
# create an array of server:services
a=($(echo "$1" | gawk 'BEGIN { FS="[]],[[]" } ; { print $1, $2, $3 }' | tr -d '[]'))
# add a for loop here to iterate values in array with code below
for var in "${a[@]}" ; do
# get server name
server1=$(echo $var | cut -d ':' -f1)
# get your services as space separated
servs1="$(echo $var | cut -d ':' -f2 | tr ',' ' ')"
# loop your services
for s in $servs1; do
ssh $server1 "service $s restart"
done
done
If you like bash programming or have to learn it this is the 'bible' to me
Advanced Bash-Scripting Guide
An in-depth exploration of the art of shell scripting
Mendel Cooper
http://www.tldp.org/LDP/abs/html/
Try this?
#!/bin/bash
SSH_IDENT_FILE=~/credentials/user.pem
SSH_USER=admin
# tells 'for' to read "per line"
IFS='
'
for line in $(
# read input from 1st command-line arg (not stdin)
echo "$1"|\
# remove all services except (nginx php-fpm mysql)
sed 's/\([:,]\)\(\(nginx\|php-fpm\|mysql\)\|[^]:,[]\+\)/\1\3/g'|\
# make it multi-line:
# server1 svc1 svc2
# server2 svc1
sed 's/\[[^]:]*:,*\]//g;s/\],*$//;s/\],*/\n/g;s/[:,]\+/ /g;s/\[//g'|\
# make it single-param:
# server1 svc1
# server1 svc2
# server2 svc1
awk '{for(i=2;i<=NF;i++)print $1" "$i}'
);do
IFS=' ' read Instance_Name service <<< $line
echo ssh -i $SSH_IDENT_FILE -o StrictHostKeyChecking=no $SSH_USER@$Instance_Name "service $service restart"
done