awscliとjqを設定


Evernoteに書き溜めている物をQiita化していくことにする。

使用環境 バージョン
Mac OS X 10.7.5
Python 2.7.6
awscli 1.3.1
jq 1.3

awscliとjqをインストール

awscli(Python2.6以上必要)

pip install awscli

#versionが上がった場合はupgradeする
pip install awscli --upgrade

jq

brew install jq

最新バージョンは1.3(2014/3/16)
binaryファイルをダウンロードして実行権限付けるだけで使用可能
http://stedolan.github.io/jq/

awscli使用準備

多数のアカウントを持っている場合はcofigにまとめて記載

awscli_account.conf
[profile < account(--profileで記述する名前) >]
aws_access_key_id = < access key >
aws_secret_access_key = < secret key>
region = < aws region >

#記述例
[profile gacharion]
aws_access_key_id = ABCDEFG
aws_secret_access_key = secret1234access
region = ap-northeast-1

#defaultは"-profile"を指定しない場合に適用される
[default]
aws_access_key_id = <default access key>
aws_secret_access_key = <default secret key>
region = <default region>

コンソール起動時にtab補完が効くようにする。
また、上記confのパスを設定しないと"--profile"で指定できないのでexportしておく。

.bashrc
# tab補完
complete -C aws_completer aws
# "--profile"でアカウント指定する際の情報を記載したconfig
export AWS_CONFIG_FILE=/home/gacharion/awscli_account.conf
# regionのdefaultを東京リージョンに(⬆のconfigでも指定しているので、どちらかで大丈夫)
export AWS_DEFAULT_REGION=ap-northeast-1
# zshの場合のtab補完は下記
# virtualenv環境の場合
source ~/.virtualenvs/2.7.6/bin/aws_zsh_completer.sh

使い方

$ aws --version
aws-cli/1.3.1 Python/2.7.6 Darwin/11.4.2

$ jq

jq - commandline JSON processor [version 1.3]
Usage: jq [options] <jq filter> [file...]

For a description of the command line options and
how to write jq filters (and why you might want to)
see the jq manpage, or the online documentation at
http://stedolan.github.com/jq

AvailabilityZone毎のスポットインスタンス台数をとる例

$ aws ec2 describe-spot-instance-requests \
    --profile gacharion \
    | jq '[ .SpotInstanceRequests[] | { LaunchedAvailabilityZone } ] | group_by(.LaunchedAvailabilityZone) | .[] | .[0] + { "Count": length }'