Skip to content

Instantly share code, notes, and snippets.

@joeljacobs
Created September 16, 2017 00:07
Show Gist options
  • Save joeljacobs/15bab8d7d7a2e6afb59c7a266af74244 to your computer and use it in GitHub Desktop.
Save joeljacobs/15bab8d7d7a2e6afb59c7a266af74244 to your computer and use it in GitHub Desktop.
Bash threaded parallel with getopt example
#!/bin/bash
OPTS=`getopt -o vhns: --long service:,sha:,server: -n 'parse-options' -- "$@"`
fail=false
if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
eval set -- "$OPTS"
servers=()
while true; do
case "$1" in
--service ) service=$2; shift 2 ;;
--sha ) sha=$2; shift 2 ;;
--server ) servers+="$2"; servers+=","; shift 2 ;;
-- ) shift; break ;;
* ) break ;;
esac
done
servers=$(echo "$servers"|tr "," " ")
if [ -z "$servers" ]; then
servers=("default" "default" "default")
echo "servers using the default of ${servers[@]}"
fi
if [ -z "$service" ]; then
echo "service must be specified"
exit 1
fi
if [ -z "$sha" ]; then
echo "sha must be specified"
exit 1
fi
function printreport {
echo
echo puppet run for $1:
cat /dev/shm/puppetmp-$1
rm /dev/shm/puppetmp-$1
echo
}
if ssh yourmom@home "cd <directory>;<command> --servers ${servers[@]} --service ${service} --sha ${sha}"
then
for i in ${servers[@]}
do
ssh <user>@$i "puppet agent -t --tags <tags>" >/dev/shm/puppetmp-$i 2>&1 &
PIDARRAY+=($!:$i)
done
for j in ${PIDARRAY[@]}
do
PID=$(echo $j|cut -d : -f 1)
SERVER=$(echo $j|cut -d : -f 2)
wait $PID
STATUS=$?
if [[ $STATUS -eq 0 ]] || [[ $STATUS -eq 2 ]]; then
printf "\e[34m$SERVER PUPPET ran OK.\e[0m\n"
printreport $SERVER
else
printf "\e[31m$SERVER PUPPET FAILED\e[0m\n"
printreport $SERVER
fail=true
fi
done
else
printf "Running heira update script (\e[34m<scriptname>\e[0m) \e[31mFAILED\e[0m\n"
fail=true
fi
if $fail; then
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment