Wednesday, December 9, 2009

Quick tip: Deploying command on multiple servers (easy script)

When you maintain hundreds of server, A good sysadmin starts to design scripts that make his life easier. Let me show you what I do.

First make sure you have a file with a the list of server names or IPs.

#cat server.list
1.1.1.1
2.2.2.2
3.3.3.3

Second make sure you have setup ssh keys from your machine (user root) to all the machines on the list. This is the only part that can be complicated, however if you have deployed machines using a Kickstart server you can make sure that all the server on pools use the same auth keys on root directory.

Now you can create the script.

#!/bin/sh
for i in `cat $1`
do
ssh -o ConnectTimeout=10 -o BatchMode=yes $i $2;
done

Very simple right. I will call it run.sh.

Let me explain it really quick.
The script will take every line of file (IP or name) and it will ssh to that machine so it can run $2 (command).
The Option ConnectTimeout will guarantee that the ssh will try to connect for 10 seconds.
Batchmode will guarantee that no password will be asked so the ssh connection will pass.


Then you can use it ....


#./run.sh server.list "/etc/init.d/apache restart"

Very helpful to restart apache on a Web server Farm.

Let's add something else to the script.

The script performs commands sequentially meaning that it has to wait until the command finishes to continue with the next server. But if you want to perform the command at the same time in all the servers we need to add the flag -f to the ssh command.

Change

ssh -o ConnectTimeout=10 -o BatchMode=yes $i $2;

to

ssh -f -o ConnectTimeout=10 -o BatchMode=yes $i $2;

Done

Enjoy it....

No comments:

Post a Comment