Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumoshu/10799220 to your computer and use it in GitHub Desktop.
Save mumoshu/10799220 to your computer and use it in GitHub Desktop.
#!/bin/sh
#
# 前提
#
# awscliとjqをインストールしておくこと
# Mac OS Xならそれぞれbrew install awscliとbrew install jqでOK
# DEBUG=1 ec2-ipaddr hoge
# などと実行すると、デバッグモードになる
# デバッグモードでは、内部的に実行されるコマンドがすべてロギングされる
if [ "$DEBUG" != "" ]; then
set -vx
fi
# ec2-api-toolsだと以下のようにできるが、不完全。Elastic IPが割り当てられているインスタンスのときIPアドレス以外のものを出力してしまう
# そういう場合分けが面倒なのでawscliを使う
#ec2-describe-instances -F tag:Name=$1 | grep INSTANCE | awk '{ FS = "\t" } { print $13 }'
# インスタンスの名前、パブリックIPアドレス、インスタンスIDのいずれかがこのスクリプトの第一引数と完全一致するインスタンスの
# パブリックIPアドレスを出力する
aws ec2 describe-instances --output json | jq -r "$(
cat <<EOF
[.Reservations[].Instances[] | select(.PublicIpAddress == "$1" or (.Tags[] | select(.Key = "Name") | .Value) == "$1" or .InstanceId == "$1") | { InstanceId\
, Name: (.Tags[] | select(.Key == "Name") | .Value), PublicIpAddress}] | .[0] | .PublicIpAddress
EOF
)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment