この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
主張(3行)
- インスタンス名とID、IPアドレスくらいをさくっと知りたい
- そのためだけにマネジメントコンソール(MC)を開くのはめんどくさい3
- awscliだと情報多すぎる3、JSONはちょっと見にくい3、
--output table
つけても同様3
というわけで
とりあえず必要な情報だけさくっと一覧できるようにしたい、と思ってついカッとなって書きました。4
awscliが動くことが前提です。
というか、やっていることは単にaws cliが吐き出すJSONをパースして欲しい情報を選んで出力しているだけです。
プロファイルなどの設定も済んでいる状態で実行して下さい。
#!/usr/bin/env ruby
# coding: utf-8
# usage: $0 [some options for `aws ec2`]
require 'json'
line_format = "%-19s %-23s %-11s %-15s %-15s %-12s %-16s %s"
line_length = 142
# command line
aws_cli_cmd = ["aws","ec2",ARGV,"describe-instances"].join(" ")
# header
puts line_format % [
"InstanceID","Name","Status","PublicIP","PrivateIP","InstanceType","AvailabilityZone","LaunchTime"
]
puts "-" * line_length
# run aws cli and parse
JSON.parse(%x(#{aws_cli_cmd}))["Reservations"].each{|n|
# ReservationId loop
n["Instances"].each{|i|
puts line_format % [
i["InstanceId"],
if i.has_key?("Tags") then i["Tags"].find{|tag| tag["Key"] == "Name" }["Value"] else "" end,
i["State"]["Name"],
if i.has_key?("PublicIpAddress") then i["PublicIpAddress"] else "" end,
if i.has_key?("PrivateIpAddress") then i["PrivateIpAddress"] else "" end,
i["InstanceType"],
i["Placement"]["AvailabilityZone"],
i["LaunchTime"]
]
}
}
# footer
puts "-" * line_length
puts "%#{line_length}s" % [aws_cli_cmd]
これをとりあえずaws-ec2-summary
などと名前をつけて保存して、
実行権限をつけておきます。
$ chmod +x ./aws-ec2-summary
実行例
$ ./aws-ec2-summary --profile individual
InstanceID Name Status PublicIP PrivateIP InstanceType AvailabilityZone LaunchTime
----------------------------------------------------------------------------------------------------------------------------------------------
i-0b8e26ac3f34bxxxx host02b stopped 172.31.23.xxx t2.nano ap-northeast-1a 2017-01-27T05:48:11.000Z
i-0994e11ea8047xxxx host02a running 13.112.75.xxx 172.31.28.xxx t2.nano ap-northeast-1a 2017-01-27T05:48:11.000Z
i-03ad5a16abd1cxxxx host01 terminated t2.nano ap-northeast-1a 2017-01-27T04:05:54.000Z
----------------------------------------------------------------------------------------------------------------------------------------------
aws ec2 --profile individual describe-instances
この様に--profile
を渡せます。
実際に実行しているaws cliコマンドラインも出力しているので、
もっと詳しい情報が欲しいときは、
$ aws ec2 --profile individual describe-instances | jq .
$ aws ec2 --profile individual describe-instances --instance-ids i-03ad5a16abd1cxxxx | jq .
のようにすれば良いかなと思います。
言い訳
- macOS Sierra の環境 (Ruby version 2.0.0)
- aws-cli version 1.11.37
の環境でしか動作確認していません。
また、取り敢えず動けばいい感じで書いたので、ろくにエラー処理などもしていません。
特にARGV
直埋め込みとかひどいコードなので、あくまで個人的な利用に留めて下さい。
もし「使いたい」という余裕のない方がいらっしゃいましたら、どうぞご自由にお持ち帰り下さい。改変もご自由にどうぞ。