AWS CLIを使ってEC2の作成や削除


概要

コンソールでポチポチ作成していたが、管理がしんどくなりそうだったのでCLIに移行。
個人的なメモに近いですが何かのお役に立てれば幸いです。
help見れば大体なんとかなりますが、しんどい人も多いと思うので。

環境

$ jq --version
jq-1.5

$ aws --version
aws-cli/1.14.30 Python/3.6.4 Darwin/16.7.0 botocore/1.8.34

EC2作成

EC2作成

$ aws ec2 run-instances \
--image-id ami-xxxxx \
--count 1 \
--instance-type t2.micro \
--subnet-id subnet-xxxxx \
--private-ip-address 10.0.0.0 \
--security-group-ids sg-xxxxx \
--key-name test_key \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=ec2-test}]' 'ResourceType=volume,Tags=[{Key=Name,Value=volume-test}]' \
--block-device-mappings '{"DeviceName":"/dev/xvda", "Ebs":{"VolumeSize":20,"VolumeType":"gp2"}}'

作成と同時にEBSにどうやってTagをつければいいのか困っていたが「--tag-specifications」をつかえばいいらしい。
オプション多いよって思う場合は[--generate-cli-skeleton」を使ってjsonを読み込むようにするとスッキリします。

EIP作成

$ aws ec2 allocate-address --domain vpc

EIPのアタッチ

$ aws ec2 associate-address --instance-id xxxxx --allocation-id xxxxx

EC2削除

EIPのデタッチ

$ aws ec2 disassociate-address --association-id xxxxx

EIP開放

$ aws ec2 release-address --allocation-id xxxxx

EC2削除

$ aws ec2 terminate-instances --instance-ids xxxxx

その他よく使う操作

EIP確認

$ aws ec2 describe-addresses| jq '.Addresses[]'

EC2ストップ

$ aws ec2 stop-instances --instance-ids xxxxx

EC2スタート

$ aws ec2 start-instances --instance-ids xxxxx

EC2再起動

$ aws ec2 reboot-instances --instance-ids xxxxx

EC2一覧確認

$ aws ec2 describe-instances | jq '.Reservations[].Instances[] | {InstanceId, PublicIpAddress, PrivateIpAddress, State, Tags}'

EC2一覧確認(起動中の物のみ)

$ aws ec2 describe-instances | jq '.Reservations[].Instances[] | {InstanceId, PublicIpAddress, PrivateIpAddress, State, Tags} | select(.State.Name == "running")'

EC2タグ検索

$ aws ec2 describe-instances | jq '.Reservations[].Instances[] | {InstanceId, PublicIpAddress, PrivateIpAddress, State, Tags} | select(.Tags[].Key == "Name" and .Tags[].Value == "ec2-test")'