Skip to content

Instantly share code, notes, and snippets.

@jfut
Created December 29, 2022 01:30
Show Gist options
  • Save jfut/57a1eea67b6e6e521ecf96768cf92ae5 to your computer and use it in GitHub Desktop.
Save jfut/57a1eea67b6e6e521ecf96768cf92ae5 to your computer and use it in GitHub Desktop.
aws-login
#!/bin/bash
#
# AWS login to the management console or instance with Session Manager or SSH
#
# Require: aws-vault
#
# Copyright (c) 2022 Jun Futagawa (jfut)
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
set -uo pipefail
# Usage
usage() {
cat << _EOF_
Usage:
$(basename ${0}) [-p] [-c] [-s] [-u USERNAME] [TARGET_FILTER]
Options:
-p Profile (Default: AWS_PROFILE environment variable)
-c Console login
-s Use SSH login
-u Username for SSH login (Default: ec2-user)
Examples:
Login to the management console with AWS_PROFILE environment variable
$(basename ${0}) -c
Login to the management console the specified profile
$(basename ${0}) -c -p profile1
Login to instance with Session Manager
$(basename ${0})
Filter target instances and login with Session Manager
$(basename ${0}) web
Filter target instances and login with SSH using admin user
$(basename ${0}) -s -u admin web
_EOF_
}
console_login() {
aws-vault login "${AWS_PROFILE}"
}
instance_login() {
# List
declare -a TARGET_ARRAY=()
INSTANCE_LIST=$(aws ec2 describe-instances \
--query 'Reservations[*].Instances[].[ Tags[?Key==`Name`] | [0].Value, InstanceId, PublicIpAddress, PrivateIpAddress, State.Name ]' \
--output json \
| jq -r '.[] | @csv' | sed 's/"//g' | sort | grep "running$" \
| egrep ${TARGET_FILTER})
for INSTANCE_INFO in ${INSTANCE_LIST}
do
INSTANCE_ID=$(echo ${INSTANCE_INFO} | cut -d',' -f 2)
TARGET_ARRAY+=(${INSTANCE_ID})
echo "- $(( ${#TARGET_ARRAY[@]} )): ${INSTANCE_INFO}"
done
# Select
if [[ ${#TARGET_ARRAY[@]} -eq 0 ]]; then
echo "ERROR: Target running instance not found."
return
elif [[ ${#TARGET_ARRAY[@]} -eq 1 ]]; then
TARGET_INSTANCE=${TARGET_ARRAY[0]}
else
echo -n "Select the instance [1..${#TARGET_ARRAY[@]}]: "
read i
TARGET_INSTANCE="${TARGET_ARRAY[$(( ${i} - 1 ))]}"
fi
# Login
if [[ "${USE_SSH}" -eq 1 ]]; then
echo "ssh ${USERNAME}@${TARGET_INSTANCE}"
ssh "${USERNAME}@${TARGET_INSTANCE}"
else
echo "aws ssm start-session --target ${TARGET_INSTANCE}"
aws ssm start-session --target "${TARGET_INSTANCE}"
fi
}
# Main
main() {
AWS_CONSOLE_LOGIN_MODE=0
AWS_PROFILE="${AWS_PROFILE}"
USE_SSH=0
USERNAME="ec2-user"
while getopts cp:su:h OPT; do
case "${OPT}" in
"c" )
AWS_CONSOLE_LOGIN_MODE=1 ;;
"p" )
AWS_PROFILE="${OPTARG}" ;;
"s" )
USE_SSH=1 ;;
"u" )
USERNAME="${OPTARG}" ;;
"h" )
usage
exit 0
;;
* )
usage
exit 1
;;
esac
done
shift $((OPTIND - 1))
TARGET_FILTER=${1:-"^"}
if [[ "${AWS_CONSOLE_LOGIN_MODE}" -eq 1 ]]; then
console_login
else
instance_login
fi
}
[[ ${#BASH_SOURCE[@]} = 1 ]] && main "${@}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment