Skip to content

Instantly share code, notes, and snippets.

@saidie
Created April 15, 2018 05:07
Show Gist options
  • Save saidie/a479d1c01fc90e5f54638318b5352e03 to your computer and use it in GitHub Desktop.
Save saidie/a479d1c01fc90e5f54638318b5352e03 to your computer and use it in GitHub Desktop.
# $HOME/.aws_util
#
# source this file in .bashrc or .zshrc
lsec2s () {
aws ec2 describe-instances --filter "Name=instance-state-name,Values=running" --query 'Reservations[].Instances[].{ id: InstanceId, name: Tags[?Key==`Name`].[Value][0][0], role: Tags[?Key==`Role`].[Value][0][0], ip: PrivateIpAddress }'
}
lsname () {
lsec2s | jq "[.[] | select(.name == \"$1\") | .ip]" | jq -r ".[]"
}
lsrole () {
if [ $# = 1 ]; then
if [ -z "$1" ]; then
lsec2s | jq "[.[] | select(.role == null) | .ip]" | jq -r ".[]"
else
lsec2s | jq "[.[] | select(.role == \"$1\") | .ip]" | jq -r ".[]"
fi
else
lsec2s | jq "[.[] | select(.role != null) | .role] | unique" | jq -r ".[]"
fi
}
lsid () {
lsec2s | jq "[.[] | select(.id == \"$1\") | .ip]" | jq -r ".[]"
}
sshrole () {
ip=`lsrole $@ | perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;'`
ssh $ip
}
run_on_role () {
role=$1
shift
for i in `lsrole $role`; do
ssh -oStrictHostKeyChecking=no $i $@
done
}
roled_ips () {
lsec2s | jq "group_by(.role) | .[] | [{role: [.[] | .role][0], ips: [.[] | .ip]}]"
}
run_on_all () {
for ip in `lsrole ''`; do
echo "$ip (-)"
ssh -oStrictHostKeyChecking=no -oConnectTimeout=5 $ip $@ 2> /dev/null
done
for role in `lsrole`; do
ip=`lsrole $role | perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;'`
echo "$ip ($role)"
ssh -oStrictHostKeyChecking=no -oConnectTimeout=5 $ip $@ 2> /dev/null
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment