Last active
November 22, 2018 12:33
-
-
Save plainas/ff7e9a0e002373dd918bbe8ad29a237e to your computer and use it in GitHub Desktop.
This file contains 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 | |
function F_get_instance_state { | |
aws ec2 describe-instances --instance-id $1 | jq -r ".Reservations[0].Instances[0].State.Name" | |
} | |
function F_get_volume_state { | |
aws ec2 describe-volumes --volume-ids $1 | jq -r ".Volumes[0].State" | |
} | |
function F_get_instance_public_ip { | |
aws ec2 describe-instances --instance-ids $1 | jq -r ".Reservations[0].Instances[0].PublicIpAddress" | |
} | |
function F_get_volume_id_from_instance { | |
aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=$1 | jq -r ".Volumes[0].VolumeId" | |
} | |
function F_create_volume_from_snapshot { | |
aws ec2 create-volume --availability-zone eu-west-1a --snapshot-id $1 \ | |
--tag-specifications "ResourceType=volume,Tags=[{Key=Name,Value=$2}]" \ | |
--volume-type gp2 | jq -r ".VolumeId" | |
} | |
function F_wait_for_instance_state { | |
local I_ID=$1 | |
local STATE=$2 | |
while [ $(F_get_instance_state $I_ID ) != $STATE ]; do | |
echo "Waiting for instance $I_ID $STATE state... Current state:" $(F_get_instance_state $I_ID) | |
sleep 1 | |
done | |
} | |
function F_wait_for_volume_state { | |
local V_ID=$1 | |
local STATE=$2 | |
while [ $(F_get_volume_state $V_ID) != $STATE ]; do | |
echo "Waiting for volume $V_ID $STATE state... Current state " $(F_get_volume_state $V_ID) | |
sleep 1 | |
done | |
} | |
OLD_VOLUME_ID=$( F_get_volume_id_from_instance $TARGET_EC2_INSTANCE_ID) | |
NEW_VOLUME_ID=$(F_create_volume_from_snapshot $CLEAN_UBUNTU_INSTALL_SNAPSHOT_ID $NEW_VOL_NAME) | |
aws ec2 stop-instances --instance-ids $TARGET_EC2_INSTANCE_ID | |
F_wait_for_instance_state $TARGET_EC2_INSTANCE_ID "stopped" | |
aws ec2 detach-volume --volume-id $OLD_VOLUME_ID | |
F_wait_for_volume_state $NEW_VOLUME_ID "available" | |
aws ec2 attach-volume --volume-id $NEW_VOLUME_ID --instance-id $TARGET_EC2_INSTANCE_ID --device /dev/sda1 | jq . | |
F_wait_for_volume_state $NEW_VOLUME_ID "in-use" | |
aws ec2 start-instances --instance-ids $TARGET_EC2_INSTANCE_ID | jq . | |
F_wait_for_instance_state $TARGET_EC2_INSTANCE_ID "running" | |
INSTANCE_PUBLIC_IP=$(F_get_instance_public_ip $TARGET_EC2_INSTANCE_ID) | |
scp -o "UserKnownHostsFile /dev/null" -o "StrictHostKeyChecking no" -i $INSTANCE_SSH_KEY deploy/install_environment.sh ubuntu@$INSTANCE_PUBLIC_IP:/home/ubuntu/ | |
ssh -t -o UserKnownHostsFile=/dev/null -o "StrictHostKeyChecking no" -i $INSTANCE_SSH_KEY ubuntu@$INSTANCE_PUBLIC_IP "sudo /home/ubuntu/install_environment.sh" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment