LoginSignup
11
10

More than 5 years have passed since last update.

AWS CLI で取得したEC2インスタンス一覧を jq で絞ってソートする

Last updated at Posted at 2017-07-04

ハマったので備忘録。

環境

Amazon Linux or CentOS
aws-cli 1.11.83
jq 1.5

やりたいこと

EC2インスタンスを対象のタグで絞ってインスタンス名のソートで表示する

CLI
$ aws ec2 describe-instances \
--filter "Name=tag:Name,Values=sono*" | 
jq -r '.Reservations[].Instances[] |
 [.Tags[] | select(.Key == "Name").Value][] + "\t" +  .InstanceId + "\t" +
 .PublicIpAddress + "\t" +  .PrivateIpAddress' | sort
結果
sono1   i-0X0X0979e008fd5f8 54.70.109.00    10.0.4.000
sono2   i-0X0X06f7ucd19029a 54.70.109.000   10.0.4.000
sono3   i-0X0X0p8e699ae08ab 54.70.109.00    172.31.10.00
sono4   i-0X0X0oebe92d37784 34.210.182.00   10.0.4.00
sono5   i-0X0X0564fb43b1fd6 34.210.192.000  172.31.15.00
sono6   i-0X0X095cb7ae6998b 54.70.210.00    10.0.1.00
sono7   i-0X0X093e5e6e008ed 35.164.127.00   172.31.13.000
sono8   i-0X0X0rc9854d1db65 52.33.146.000   172.31.3.000
sono9   i-0X0X08d243309f8cb 35.166.176.00   172.31.13.000

1. EC2のインスタンス一覧の表示

aws ec2 describe-instances 

2. タグの前方一致検索

--filter "Name=tag:Name,Values=sono*" 

3. 結果をタブ区切りで表示

jq -r '.Reservations[].Instances[] |
 .Tags[].Value + "\t" +  .InstanceId + "\t" +
 .PublicIpAddress + "\t" +  .PrivateIpAddress'

4. 並べ替え

 | sort

次に検討中なこと

@tsv を使うと警告がでるので調査してみる。

CLI
$ aws ec2 describe-instances | \
    jq -r '.[][].Instances[]
         | [[.Tags[] | select(.Key == "Name").Value][],
            .InstanceId,
            .PublicIpAddress,
            .PrivateIpAddress,
            .InstanceType]
         | @tsv' | sort 
エラー
jq: error (at <stdin>:1210): Cannot iterate over null (null)

Tips

CentOS6にpipをインストール

rpm -iUvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install python-pip

pip のアップデート

$ pip install --upgrade pip

aws-cli のインストール

$ pip install awscli

JSONパーサ jq コマンドのインストール

$ sudo yum install jq

使う前に認証してから

$ aws configure

すべてのインスタンス一覧の取得

$ aws ec2 describe-instances | jq '.Reservations[].Instances[]'

実行結果を複数カラムに分けて整形(プロンプト上で縦がそろう)

column -t

実行したディレクトリに結果ファイルを出力(末尾に追加)

--output result

削除保護の無効化

instance1個
$ aws ec2 modify-instance-attribute --instance-id i-0X0X0X0X --no-disable-api-termination
instance複数
$ aws ec2 modify-instance-attribute --instance-id i-0X0X0X0X --instance-id i-0X0X0X0X --no-disable-api-termination

稼働中インスタンス一覧の取得

aws ec2 describe-instances \
--filter "Name=instance-state-name,Values=running" | 
jq -r '.Reservations[].Instances[] |
 .Tags[].Value + "\t" +  .InstanceId + "\t" +
 .PublicIpAddress + "\t" +  .PrivateIpAddress' | sort

インスタンスの削除

aws ec2 terminate-instances --instance-ids i-0X0X0c9854d1db65
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10