Last active
September 19, 2023 08:47
-
-
Save dex4er/e5fb2bfe979d8960364d30f9c24f5911 to your computer and use it in GitHub Desktop.
ssm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
## ssm | |
## | |
## Copyright (c) 2023 Piotr Roszatycki <[email protected]>, MIT | |
set -e | |
if ! command -v aws >/dev/null; then | |
echo "Needs aws command." | |
open https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html | |
exit 1 | |
fi | |
if ! command -v session-manager-plugin >/dev/null; then | |
echo "Needs session-manager-plugin command." | |
open https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html | |
exit 1 | |
fi | |
host=$1 | |
shift | |
if [[ -z $host ]]; then | |
echo "Usage: $0 HOST [--profile PROFILE] ARGS" | |
exit 1 | |
fi | |
stty_restore () { | |
stty discard ^O dsusp ^Y eof ^D erase "^?" intr ^C kill ^U lnext ^V quit ^\\ reprint ^R start ^Q status ^T stop ^S susp ^Z werase ^W | |
} | |
stty_undef () { | |
trap stty_restore EXIT | |
stty discard undef dsusp undef eof undef erase undef intr undef kill undef lnext undef quit undef reprint undef start undef status undef stop undef susp undef werase undef | |
} | |
args=($@) | |
profile=${AWS_PROFILE:-default} | |
for ((i=0; i<${#args[@]}; i++)); do | |
if [[ ${args[$i]} == "--profile" ]]; then | |
((i++)) || true | |
profile=${args[$i]} | |
fi | |
done | |
case "$host" in | |
i-*) | |
stty_undef | |
aws ssm start-session --profile "$profile" --target "$host" "${args[@]}";; | |
*) | |
instance=$( | |
aws ec2 describe-instances \ | |
--profile "$profile" \ | |
--filters "Name=tag:Name,Values=$host" "Name=instance-state-name,Values=running" \ | |
--query "Reservations[].Instances[0].InstanceId" \ | |
--max-items 1 \ | |
--output text | | |
head -n1 | |
) | |
echo Instance: $instance | |
if [[ -n $instance ]]; then | |
stty_undef | |
aws ssm start-session --profile "$profile" --target "$instance" "${args[@]}" | |
fi | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment