Skip to content

Instantly share code, notes, and snippets.

@tkuchiki
Last active December 7, 2015 17:16
Show Gist options
  • Save tkuchiki/eff871293525d23d2c05 to your computer and use it in GitHub Desktop.
Save tkuchiki/eff871293525d23d2c05 to your computer and use it in GitHub Desktop.
mackerel のホスト一覧をファイルに書いて、ssh 補完できるようにする (required jq)
# ~/.ssh/config
_known_hosts_real()
{
export NSS_SDB_USE_CACHE=yes
local config_file=~/.ssh/config
local ctime=0
[ -f $config_file ] && ctime=$(stat -c %Y $config_file)
local t=$(($(date +%s) - $ctime))
local interval=60
local search_word="# mackerel"
if [ $t -ge $interval ]; then
local apikey=$(cat /etc/mackerel-agent/mackerel-agent.conf | grep ^apikey | awk '{ $key = substr($3, 2); sub(/.$/,"",$key); print $key }')
local hosts=$(curl -s https://mackerel.io/api/v0/hosts.json -H "X-Api-Key: ${apikey}" | jq -r '.hosts[] | select(.status != "poweroff") | "\(.name) \(.meta.cloud.metadata["local-ipv4"])"' | xargs -I{} echo {} "${search_word}")
if [ $? -eq 0 ]; then
[ -f $config_file ] && sed -i "/${search_word}/,+2d" $config_file
echo "${hosts}" | awk -v comment="${search_word}" '{printf("Host %s %s\nHostname %s\n", $1, comment, $2)}' >> $config_file
fi
fi
local comp_hosts=$(grep "${search_word}" $config_file | awk '{printf("%s ", $2)}')
COMPREPLY=( $( \
compgen -W "${comp_hosts}" \
${COMP_WORDS[COMP_CWORD]} \
) )
return 0
}
# /etc/hosts
_known_hosts_real()
{
export NSS_SDB_USE_CACHE=yes
local config_file=/etc/hosts
local ctime=0
[ -f $config_file ] && ctime=$(stat -c %Y $config_file)
local t=$(($(date +%s) - $ctime))
local interval=60
local search_word="# mackerel"
if [ $t -ge $interval ]; then
local apikey=$(cat /etc/mackerel-agent/mackerel-agent.conf | grep ^apikey | awk '{ $key = substr($3, 2); sub(/.$/,"",$key); print $key }')
local hosts=$(curl -s https://mackerel.io/api/v0/hosts.json -H "X-Api-Key: ${apikey}" | jq -r '.hosts[] | select(.status != "poweroff") | "\(.meta.cloud.metadata["local-ipv4"]) \(.name)"' | xargs -I{} echo {} "${search_word}")
if [ $? -eq 0 ]; then
[ -f $config_file ] && sed -i '/# mackerel/d' $config_file
echo "${hosts}" >> $config_file
fi
fi
local comp_hosts=$(grep "${search_word}" $config_file | awk '{printf("%s ", $2)}')
COMPREPLY=( $( \
compgen -W "${comp_hosts}" \
${COMP_WORDS[COMP_CWORD]} \
) )
return 0
}
#!/bin/bash
set -e
export NSS_SDB_USE_CACHE=yes
config_file=/etc/hosts
search_word="# mackerel"
apikey=$(cat /etc/mackerel-agent/mackerel-agent.conf | grep ^apikey | awk '{ $key = substr($3, 2); sub(/.$/,"",$key); print $key }')
hosts=$(curl -s https://mackerel.io/api/v0/hosts.json -H "X-Api-Key: ${apikey}" | jq -r '.hosts[] | select(.status != "poweroff") | "\(.meta.cloud.metadata["local-ipv4"]) \(.name)"' | xargs -I{} echo {} "${search_word}")
[ -f $config_file ] && sed -i '/# mackerel/d' $config_file
echo "${hosts}" >> $config_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment