JSON から AWS CLI でインスタンス起動
自分使いのスクリプト
バージョン
$ aws --version aws-cli/1.7.3 Python/2.7.6 Darwin/14.0.0
スクリプト
ホスト名を引数にして実行。 --cli-input-json オプションを使う。
#!/bin/sh role=$1 host=$2 cd `(dirname $0)` AWS="/usr/local/bin/aws --region ap-northeast-1" JSON_FILE="file://./${role}/${host}.json" USER_DATA="file://./${role}/user-data" INSTANCE_ID=`${AWS} ec2 run-instances \ --cli-input-json ${JSON_FILE} \ | jq -r '.Instances[].InstanceId'` ${AWS} ec2 create-tags \ --resources ${INSTANCE_ID} \ --tags Key=Name,Value=$1 IP_ADDR=`${AWS} ec2 describe-instances --instance-id ${INSTANCE_ID} \ | jq -r '.Reservations[].Instances[].PrivateIpAddress'` echo "started instance. Name => $1 IP => ${IP_ADDR} InstanceId => ${INSTANCE_ID}"
json
--cli-input-json オプションを流し込むためのひな形を下記コマンドで取得する。
aws ec2 run-instances --generate-cli-skeleton
以下の様なひな形ができる。
値のない key は削除しないとエラーになる。
{ "DryRun": true, "ImageId": "", "MinCount": 0, "MaxCount": 0, "KeyName": "", "SecurityGroups": [ "" ], "SecurityGroupIds": [ "" ], "UserData": "", "InstanceType": "", "Placement": { "AvailabilityZone": "", "GroupName": "", "Tenancy": "" }, "KernelId": "", "RamdiskId": "", "BlockDeviceMappings": [ { "VirtualName": "", "DeviceName": "", "Ebs": { "SnapshotId": "", "VolumeSize": 0, "DeleteOnTermination": true, "VolumeType": "", "Iops": 0, "Encrypted": true }, "NoDevice": "" } ], "Monitoring": { "Enabled": true }, "SubnetId": "", "DisableApiTermination": true, "InstanceInitiatedShutdownBehavior": "", "PrivateIpAddress": "", "ClientToken": "", "AdditionalInfo": "", "NetworkInterfaces": [ { "NetworkInterfaceId": "", "DeviceIndex": 0, "SubnetId": "", "Description": "", "PrivateIpAddress": "", "Groups": [ "" ], "DeleteOnTermination": true, "PrivateIpAddresses": [ { "PrivateIpAddress": "", "Primary": true } ], "SecondaryPrivateIpAddressCount": 0, "AssociatePublicIpAddress": true } ], "IamInstanceProfile": { "Arn": "", "Name": "" }, "EbsOptimized": true }
- host.json とかそんな風にして以下の様に編集。
{ "DryRun": false, "ImageId": "ami-*******", "KeyName": "*****", "SecurityGroupIds": [ "sg-**********" ], "InstanceType": "t2.small", "Placement": { "AvailabilityZone": "ap-northeast-1b", "Tenancy": "default" }, "BlockDeviceMappings": [ { "VirtualName": "root-device", "DeviceName": "/dev/sda1", "Ebs": { "VolumeSize": 30, "DeleteOnTermination": true, "VolumeType": "standard" }, "NoDevice": "" } ], "Monitoring": { "Enabled": true }, "SubnetId": "subnet-********", "DisableApiTermination": false, "PrivateIpAddress": "10.0.0.10", "IamInstanceProfile": { "Name": "web_servers" }, "EbsOptimized": false }
IamInstanceProfile は IAM Role の名前だけでよい。
ドキュメントには Arn と Name を指定するように書かれていたが、
上記以外では下記のようなエラーが出力された。
A client error (InvalidParameterCombination) occurred when calling the RunInstances operation: The parameter 'iamInstanceProfile.name' may not be used in combination with 'iamInstanceProfile.arn'