Skip to content

Instantly share code, notes, and snippets.

@yudoufu
Last active February 16, 2021 05:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yudoufu/9be2f5a54b4e509c2df79db0c2c13f4b to your computer and use it in GitHub Desktop.
Save yudoufu/9be2f5a54b4e509c2df79db0c2c13f4b to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
usage() {
echo "USAGE: `basename $0` [Options]"
echo " ssm target selection using peco"
echo ""
echo "Optinal Arguments:"
echo " All arguments excluded options pass to initial queries of peco"
echo ""
echo "Options:"
echo " -h, --help show this help."
echo " -p, --profile select aws profile.(default: 'default')"
echo " -v, --verbose show detail commands."
echo " --dry dry run mode."
echo ""
echo "Dependent packages:"
echo " aws-cli, ssm-plugin, peco"
exit 1;
}
main() {
declare -a argv=()
while (( $# > 0 )); do
case $1 in
-h|--help) usage;;
-p|--profile) readonly profile=$2; shift;;
-v|--verbose) readonly is_verbose=1;;
--dry) readonly is_dry=1;;
-*) fatal "Unkown option: $1"; usage;;
*) argv=("${argv[@]}" "$1");;
esac
shift
done
set -- "${argv[@]}"
local query="$*"
local params=""
if [ "$profile" != "" ];then
params="$params --profile $profile"
fi
local instance=$(aws ec2 describe-instances --query 'sort_by(Reservations[].Instances[].{Id:InstanceId,Name:Tags[?Key==`Name`].Value|[0]},&Name)' --output text $params | peco --prompt="ssm profile:${profile:-default}>" --query="$query")
if [ "$instance" == "" ]; then
echo "Instance is not choosed."
exit 1
fi
local instance_id=$(echo "$instance" | cut -f 1)
run aws ssm "$params" start-session --target "$instance_id"
}
run() {
if [ $is_dry ]; then
echo "[dry run] $@"
else
if [ $is_verbose ];then
echo "[run] $@"
fi
eval "$@"
fi
}
# call main.
main "$@"
@yudoufu
Copy link
Author

yudoufu commented Jun 2, 2020

Install:

$ curl -O https://gist.githubusercontent.com/yudoufu/9be2f5a54b4e509c2df79db0c2c13f4b/raw/8e0bf92e60f01e88aedbf879f17b8c100aee27b4/ssm.sh
$ chmod +x ssm.sh

Usage:

$ ./ssm.sh --help
USAGE: ssm.sh [Options]
  ssm target selection using peco

Optinal Arguments:
  All arguments excluded options pass to initial queries of peco

Options:
  -h, --help          show this help.
  -p, --profile       select aws profile.(default: 'default')
  -v, --verbose       show detail commands.
  --dry               dry run mode.

Dependent packages:
  aws-cli, ssm-plugin, peco

For example:

Use default profile.

$ ./ssm.sh

Use specific profile.

$ ./ssm.sh --profile your_profile

Set some initial query for selection.

$ ./ssm.sh -p your_profile hoge query

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment