Skip to content

Instantly share code, notes, and snippets.

@masayoshi634
Created October 2, 2019 07:35
Show Gist options
  • Save masayoshi634/b7cf4ce233851b6377b097a8d2ecaf4b to your computer and use it in GitHub Desktop.
Save masayoshi634/b7cf4ce233851b6377b097a8d2ecaf4b to your computer and use it in GitHub Desktop.
mackerel ssh
#!/bin/sh
HOSTS_FILE="${HOME}/.hosts"
CACHE_TIME="5"
ROLES_SELECT="false"
print_help() {
cat <<-EOF >> /dev/stdout
mackerel ssh command
Depends:
mkr
peco (https://github.com/peco/peco)
Usage: $0 [-r]
Options:
-r Enable Select Mackerle Role
-h print this message and exit
EOF
}
old_cache(){
[ "$(find "${HOSTS_FILE}" -mmin -${CACHE_TIME} | wc -l)" -eq 0 ]
}
select_role(){
ROLE_NAME=$(cat ${HOSTS_FILE} | jq -r '.roles[]' 2>/dev/null | sort | uniq | peco)
}
while getopts "rh" opt; do
case ${opt} in
r ) ROLES_SELECT="true" ;;
h ) print_help; exit ;;
* ) print_help; exit 1 ;;
esac
done
shift $((OPTIND - 1))
if old_cache; then
echo 'update cache'
mkr hosts | jq -r '.[] | {"name": .name, "roles": .roleFullnames, "ip": .ipAddresses.eth0}' > ${HOSTS_FILE}
fi
if [ ${ROLES_SELECT} = "true" ]; then
select_role
HOST_NAME=$(cat ${HOSTS_FILE} | jq -r '. | select(.roles[] =="'${ROLE_NAME}'") | .name' 2>/dev/null | peco)
else
HOST_NAME=$(cat ${HOSTS_FILE} | jq -r '.name' | peco)
fi
IP=$(cat ${HOSTS_FILE} | jq -r '. | select(.name == "'${HOST_NAME}'") | .ip')
echo ${ROLE_NAME}
ssh ${IP}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment