Skip to content

Instantly share code, notes, and snippets.

@justmiles
Last active November 25, 2020 16:26
Show Gist options
  • Save justmiles/37e4d22a27ea5919227ffb05546810c2 to your computer and use it in GitHub Desktop.
Save justmiles/37e4d22a27ea5919227ffb05546810c2 to your computer and use it in GitHub Desktop.
Launch console sessions using AWS Simple Systems Manager
#!/bin/bash
# ssm
# Launch console sessions using AWS Simple Systems Manager
# Requirements
# jq, aws-cli
# Usage
# ssm <instance name>
# ssm <instance id>
_ssm() {
[ -z "$AWS_PROFILE" ] && echo "AWS_PROFILE not set!" && return
CACHE="/tmp/instances_${AWS_PROFILE}.json"
find $CACHE -mmin -720 >/dev/null 2>&1 || (aws ec2 describe-instances --filters Name=instance-state-code,Values=16 >$CACHE 2>/dev/null || rm $CACHE)
# return if cache is empty
[ ! -f $CACHE ] && echo "err: unable to describe instances" && return
local cur
local IFS=$'\n'
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
echo $cur
WORDS="$(cat $CACHE | jq '.[][].Instances[] | .Tags[] | select(.Key == "Name") | .Value' | sort | uniq)"
case "$cur" in
*)
COMPREPLY=($(compgen -W "$WORDS" -- "$cur"))
;;
esac
}
function ssm() {
CACHE="/tmp/instances_${AWS_PROFILE}.json"
TARGET="$@"
REG="^i-[0-9a-z]+"
if [[ "$TARGET" =~ $REG ]]; then
INSTANCE_ID=$TARGET
TARGET=""
else
INSTANCE_ID=$(cat $CACHE | jq -r --arg v "$TARGET" '.[][].Instances[] | (select( .Tags[] | .Value == $v)) | .InstanceId' | shuf -n 1)
fi
if [ -z INSTANCE_ID ]; then
echo "No instance matching '$TARGET'"
exit 1
fi
echo $TARGET $INSTANCE_ID
aws ssm start-session --target $INSTANCE_ID
}
complete -F _ssm ssm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment