Skip to content

Instantly share code, notes, and snippets.

@rossedman
Last active November 10, 2022 21:44
Show Gist options
  • Save rossedman/ccc5586ef3661e63677766c2e84b59e6 to your computer and use it in GitHub Desktop.
Save rossedman/ccc5586ef3661e63677766c2e84b59e6 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# kubectl-otk-ssh
#
# this script provides a way to SSH/SSM into hosts. this is backed
# by AWS SSM and is not a true ssh. this scripts provides the functionality
# to select random hosts by status or labels or directly choose a host.
#
# Install:
#
# place this script anywhere in your path named `kubectl-otk-ssh`
# and then you can run it as a subcommand of `kubectl`
#
# Examples:
#
# kubectl otk ssh --hostname <hostname>
# kubectl otk ssh --random
#
set -e -o pipefail
declare hosts
declare random
declare status
declare hostname
get_host_instance_id() {
echo $(kubectl get nodes/$1 -o=custom-columns='ID:.spec.providerID' --no-headers) | cut -f5 -d/
}
get_host_region() {
echo $(kubectl get nodes/$1 -o jsonpath='{.metadata.labels.failure-domain\.beta\.kubernetes\.io/region}')
}
get_all_hosts() {
$(kubectl get nodes -o=custom-columns='ID:.spec.providerID' --no-headers)
}
main() {
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
-h | --hostname )
shift; hostname=$1
;;
-r | --random )
random=1
;;
-s | --status )
shift; status=$1
;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
# check required args are provided
if [[ -z "$hostname" ]] && [[ -z "$random" ]]; then
echo '[ERR] --hostname or --random need to be set' >&2
exit
fi
# ensure the session-manager-plugin is installed
if ! [ -x "$(command -v session-manager-plugin)" ]; then
echo '[ERR] session-manager-plugin is not installed, please run `brew install session-manager-plugin`' >&2
exit 1
fi
# if a hostname is specified ignore everything else and login
# directly to that host
if [[ -n "$hostname" ]]; then
aws ssm start-session --target $(get_host_instance_id $hostname) --region $(get_host_region $hostname)
exit 0
fi
# select all hosts
for i in $(kubectl get nodes --output name --no-headers); do
host=$(echo $i | cut -f2 -d/)
hosts+=($host)
done
# select a random host
rando=$[$RANDOM % ${#hosts[@]}]
rando=${hosts[rando]}
aws ssm start-session --target $(get_host_instance_id $rando) --region $(get_host_region $rando)
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment