Skip to content

Instantly share code, notes, and snippets.

@m1g0r
Forked from atr0s/.bash_profile
Created July 20, 2022 13:13
Show Gist options
  • Save m1g0r/d40da77a0d1053afb10f9da2187ae0a2 to your computer and use it in GitHub Desktop.
Save m1g0r/d40da77a0d1053afb10f9da2187ae0a2 to your computer and use it in GitHub Desktop.
AWS Session Manager SSH/SCP helper
# Snippet of code to be put on ~/.bash_profile to help SSH into instances via Session Manager while specifying AWS profiles
# It can be used by saving ~/.ssm_bash_profile and adding the following line to ~/.bash_profile
# source ~/.ssm_bash_profile
function aws-ssm-instance-list {
if [ "$#" -lt 1 ]; then
echo "Usage: aws-ssm-instance-list <profile name>"
else
output=$(aws ssm describe-instance-information --profile $1 --query "InstanceInformationList[*].{Name:ComputerName,Id:InstanceId,IPAddress:IPAddress}" --output text)
echo "$output"
fi
}
function aws-ssm-menu {
printf "List of instances for $1:\n\n"
instance_list_output=$(aws-ssm-instance-list $1)
IFS=$'\n'
instance_list=($instance_list_output)
unset IFS
for i in "${!instance_list[@]}"; do
printf "%s) %s\n" "$i" "${instance_list[$i]}"
done
printf "\nSelect an instance from the list above: "
IFS= read -r opt
if [[ $opt =~ ^[0-9]+$ ]] && (( (opt >= 0) && (opt < "${#instance_list[@]}") )); then
return $opt
else
printf 'invalid option\n'
return -1
fi
}
function aws-scp {
if [ "$#" -lt 2 ]; then
echo "Usage: aws-scp <profile name> <scp parameters>"
else
scp -o ProxyCommand="bash -c \"aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p' --profile $1\"" ${@:2}
fi
}
function aws-ssh {
if [ "$#" -lt 2 ]; then
echo "Usage: aws-ssh <profile name> <ssh parameters>"
else
ssh ${@:2} -o ProxyCommand="bash -c \"aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p' --profile $1\""
fi
}
function aws-ssm-session {
if [ "$#" -lt 2 ]; then
echo "Usage: aws-ssm-session <profile name> <instance_id>"
else
aws ssm start-session --target $2 --profile $1
fi
}
function aws-session-interactive {
if [ "$#" -lt 1 ]; then
echo "Usage: aws-ssh-interactive <profile name>"
else
aws-ssm-menu $1
choice=$?
if [ $choice -ne 255 ] ; then
instance_id=$(echo "${instance_list[$choice]}"| awk {'print $2'})
aws-ssm-session $1 $instance_id
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment