Last active
January 30, 2020 01:56
-
-
Save negokaz/b665930a9c30c6a1b5992c4d12cd8f79 to your computer and use it in GitHub Desktop.
AWS Dev Helper Scripts
This file contains hidden or 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
#!/bin/bash | |
# | |
# 稼働中(running)のEC2インスタンスの一覧から SSH できるようにする | |
function main { | |
local filter="$1" | |
local all_instances="$(fetch_runnning_instances)" | |
local candidate_instances="$(echo "${all_instances}" | grep --color=always "${filter}")" | |
if [[ -z "${candidate_instances}" ]] | |
then | |
echo "No match: '${filter}'" | |
local instance="$(select_instance "${all_instances}")" | |
elif [[ $(echo "${candidate_instances}" | wc --lines) -eq 1 ]] | |
then | |
echo "<<< ${candidate_instances} >>>" | |
read -p 'Press Enter key to access: ' input | |
if [[ -z "${input}" ]] | |
then | |
local instance="${candidate_instances}" | |
else | |
local instance='' | |
fi | |
else | |
local instance="$(select_instance "${candidate_instances}")" | |
fi | |
if [[ ! -z "${instance}" ]] | |
then | |
local instance_ip="$(echo "${instance}" | awk '{ print $2 }')" | |
exec ssh "${instance_ip}" | |
fi | |
} | |
function select_instance { | |
local instances="$1" | |
IFS=$'\n' PS3='Select instance: ' | |
select selected_instance in $(echo "${instances}" | display_as_table) | |
do | |
echo "${selected_instance}" | |
return 0 | |
done | |
} | |
function display_as_table { | |
column --separator $'\t' --table | |
} | |
function fetch_runnning_instances { | |
aws ec2 describe-instances \ | |
--filter 'Name=instance-state-name,Values=running' \ | |
--query 'Reservations[*].Instances[*].{_1:(Tags[?Key==`Name`].Value)[0],_2:PrivateIpAddress}[]' \ | |
--output text \ | |
| sort --field-separator=$'\t' --key=1,1 | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment