-
-
Save hostmaster/814927067c7e1ef18738194fdb5f9eb4 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env bash | |
AWS_CLI="aws --region $AWS_REGION" | |
PRICE=0.2 | |
USER_NAME=#USERNAME# | |
KEY_NAME=#KEY NAME# | |
SECURITY_GROUP_ID=#SECURITY GROUP# | |
SUBNET_ID=#SUBNET# | |
VOLUME_SIZE=40 | |
INSTANCE_TYPE=t2.2xlarge | |
BLOCK_DURATION_MINUTES=300 | |
# Ubuntu (ubuntu-bionic-18.04-amd64-server-20180912) | |
IMAGE_ID=ami-0bdf93799014acdc4 | |
SNAPSHOT_ID=snap-0607841ca97e79815 | |
SPEC=$(cat <<EOF | |
{ | |
"ImageId": "$IMAGE_ID", | |
"InstanceType": "$INSTANCE_TYPE", | |
"SubnetId": "$SUBNET_ID", | |
"KeyName": "$KEY_NAME", | |
"BlockDeviceMappings": [ | |
{ | |
"DeviceName": "/dev/sda1", | |
"Ebs": { | |
"DeleteOnTermination": true, | |
"VolumeType": "gp2", | |
"VolumeSize": $VOLUME_SIZE, | |
"SnapshotId": "$SNAPSHOT_ID" | |
} | |
} | |
], | |
"SecurityGroupIds": [ | |
"$SECURITY_GROUP_ID" | |
] | |
} | |
EOF | |
) | |
VALID_UNTIL=$(date -v +10M +%s) | |
OUTPUT=$($AWS_CLI ec2 request-spot-instances --valid-until $VALID_UNTIL --instance-count 1 --block-duration-minutes $BLOCK_DURATION_MINUTES --type "one-time" --spot-price $PRICE --launch-specification "$SPEC") | |
if [ $? -ne 0 ]; then | |
echo "Could not request spot instance: $OUTPUT" | |
exit; | |
fi | |
SPOT_INSTANCE_REQUEST_ID=$(echo $OUTPUT|jq -r '.SpotInstanceRequests[0].SpotInstanceRequestId') | |
while true; do | |
OUTPUT=$($AWS_CLI ec2 describe-spot-instance-requests --query "SpotInstanceRequests[?SpotInstanceRequestId=='$SPOT_INSTANCE_REQUEST_ID']") | |
if [ $? -ne 0 ]; then | |
echo "Error retrieving spot instance requests: $OUTPUT" | |
exit; | |
fi | |
STATUS=$(echo $OUTPUT| jq -r '.[0].Status.Code') | |
if [[ "$STATUS" == 'fulfilled' ]]; then | |
INSTANCE_ID=$(echo $OUTPUT| jq -r '.[0].InstanceId') | |
break | |
fi | |
echo "Waiting for fullfillment: $STATUS" | |
sleep 1 | |
done | |
OUTPUT=$($AWS_CLI ec2 create-tags --resources $SPOT_INSTANCE_REQUEST_ID $INSTANCE_ID --tags 'Key=SPOT,Value=SPOT') | |
if [ $? -ne 0 ]; then | |
echo "Error tagging instance ($INSTANCE_ID) for spot request ($SPOT_INSTANCE_REQUEST_ID): $OUTPUT" | |
exit; | |
fi | |
OUTPUT=$($AWS_CLI ec2 describe-instances --instance-id $INSTANCE_ID) | |
if [ $? -ne 0 ]; then | |
echo "Error retrieving instance information: $OUTPUT" | |
exit; | |
fi | |
PUBLIC_IP=$(echo $OUTPUT | jq -r '.Reservations[].Instances[0].NetworkInterfaces[0].Association.PublicIp') | |
echo "Spot instance ready, connect using: ssh $USER_NAME@$PUBLIC_IP" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment