Last active
September 15, 2016 04:33
-
-
Save nazoking/2bf7d247a2c01c7206461c10d2ec73dd to your computer and use it in GitHub Desktop.
スポットインスタンスを立ててボリュームをアタッチしてIPをHOSTファイルに保存する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
set -x | |
set -u | |
AWS_DEFAULT_REGION=us-west-1 | |
INSTANCE_TYPE=c4.2xlarge | |
# イメージID | |
IMAGE_ID=ami-xxxxxx | |
# ssh するときのユーザ名(ubuntuならubuntu、 amazon linux なら ec2-user ) | |
OS_USERNAME=ubuntu | |
# 値段 | |
PRICE=0.1 | |
# 起動スペック | |
LAUNCH_SPECIFICATION='{ | |
"ImageId": "'$IMAGE_ID'", | |
"SecurityGroupIds": [ "sg-xxxxxxx" ], | |
"InstanceType": "'${INSTANCE_TYPE}'", | |
"Placement": { | |
"AvailabilityZone": "'${AWS_DEFAULT_REGION}b'" | |
} | |
}' | |
# アタッチするボリューム | |
VOLUME_ID=vol-xxxxxxx | |
# アタッチする先 | |
VOLUME_DEVICE=/dev/xvdf | |
function request_sopt_instances() | |
{ | |
aws ec2 request-spot-instances \ | |
--region ${AWS_DEFAULT_REGION} \ | |
--spot-price $PRICE \ | |
--instance-count 1 \ | |
--launch-specification "${LAUNCH_SPECIFICATION}" \ | |
--query "SpotInstanceRequests[].SpotInstanceRequestId" \ | |
--output text | |
} | |
function wait_spot_instance() | |
{ | |
local SRI=$1 | |
aws ec2 wait spot-instance-request-fulfilled \ | |
--region ${AWS_DEFAULT_REGION} \ | |
--spot-instance-request-ids $SRI | |
} | |
function get_instance_id() | |
{ | |
local SRI=$1 | |
aws ec2 describe-spot-instance-requests \ | |
--region ${AWS_DEFAULT_REGION} \ | |
--spot-instance-request-ids $SRI \ | |
--query "SpotInstanceRequests[].InstanceId" \ | |
--output text | |
} | |
function wait_instance_running() | |
{ | |
local INSTANCE_ID=$1 | |
aws ec2 wait instance-running \ | |
--region ${AWS_DEFAULT_REGION} \ | |
--instance-ids $INSTANCE_ID | |
} | |
function get_public_ip() | |
{ | |
local INSTANCE_ID=$1 | |
aws ec2 describe-instances \ | |
--region ${AWS_DEFAULT_REGION} \ | |
--instance-ids $INSTANCE_ID \ | |
--query "Reservations[].Instances[].PublicIpAddress" \ | |
--output text | |
} | |
function attach_volume() | |
{ | |
local INSTANCE_ID=$1 | |
aws ec2 attach-volume \ | |
--region ${AWS_DEFAULT_REGION} \ | |
--volume-id ${VOLUME_ID} \ | |
--instance-id $INSTANCE_ID \ | |
--device ${VOLUME_DEVICE} | |
} | |
if [ ! 0 -eq "${#@}" ];then | |
"$@" | |
exit | |
fi | |
SRI="$(request_sopt_instances)" | |
echo SRI=$SRI | |
wait_spot_instance $SRI | |
INSTANCE_ID="$(get_instance_id $SRI)" | |
echo INSTANCE_ID=$INSTANCE_ID | |
wait_instance_running $INSTANCE_ID | |
attach_volume $INSTANCE_ID | |
PUBLIC_IP="$(get_public_ip $INSTANCE_ID)" | |
echo PUBLIC_IP=$PUBLIC_IP | |
echo ${OS_USERNAME}@$PUBLIC_IP > HOST | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
HOST
というファイルに[email protected]
というテキストが入るのでssh $(<HOST)
とするとそのホストにsshできる