Skip to content

Instantly share code, notes, and snippets.

@cliv
Created April 6, 2018 17:05
Show Gist options
  • Save cliv/20782036f7d768388c22813ef06ae053 to your computer and use it in GitHub Desktop.
Save cliv/20782036f7d768388c22813ef06ae053 to your computer and use it in GitHub Desktop.
Run command on multiple AWS hosts by name
#!/bin/bash
if [ "$#" -ne 3 ]; then
echo "Illegal number of parameters"
echo "Usage: multirunner {profile} {hostspec} {command}"
exit
fi
PROFILE=$1
HOSTSPEC=$2
COMMAND=$3
TEMPFILE="/tmp/awsHosts.txt"
echo "Getting list of hosts matching ${HOSTSPEC} from ${PROFILE}"
aws ec2 describe-instances --profile ${PROFILE} --output text --query 'Reservations[*].Instances[*].[Tags[?Key==`Name`] | [0].Value,PrivateIpAddress]' --filters "Name=tag:Name,Values=${HOSTSPEC}" "Name=instance-state-name,Values=running" | sort > $TEMPFILE
if [ "$?" -ne 0 ]; then
echo "Unable to retrieve list of hosts"
exit
fi
echo "Going to run ${COMMAND} on the following host(s):"
column -t $TEMPFILE
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
cat $TEMPFILE | while read line; do
host=$(echo $line | awk '{ print $1 }')
ip=$(echo $line | awk '{ print $2 }')
echo "$host ($ip) --"
ssh sipuser@$ip "${COMMAND}" < /dev/null
done
else
echo "Aborted."
exit
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment