Skip to content

Instantly share code, notes, and snippets.

@bobvanderlinden
Created September 3, 2018 12:01
Show Gist options
  • Select an option

  • Save bobvanderlinden/22c7de11af8ca33cc2f82060bfbaae2a to your computer and use it in GitHub Desktop.

Select an option

Save bobvanderlinden/22c7de11af8ca33cc2f82060bfbaae2a to your computer and use it in GitHub Desktop.
Run commands on multiple servers in parallel

Usage

For example create a file with multiple servers:

echo 192.168.1.1 >> production_servers

Use the file with run_on to execute a command on all servers in parallel:

./run_on.sh production_servers 'tail -f /etc/nginx/nginx_access.log'
#!/bin/bash
set -o errexit
for command in "$@"
do
$command &
done
function kill_jobs()
{
job_pids=($(jobs -p))
[ "${#job_pids[@]}" -eq 0 ] || kill "${job_pids[@]}"
}
trap 'kill_jobs' EXIT
wait
#!/bin/bash
commands=()
servers=($(cat "$1"))
shift
commands=()
for cmd in "$@"
do
for server in "${servers[@]}"
do
commands+=("ssh $server server=$server; ($cmd) 2>&1 | while read line; do echo \"\$server: \$line\"; done")
done
done
./parallel.sh "${commands[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment