From bced10714599aaac03f7645a6b663e1d368047c5 Mon Sep 17 00:00:00 2001 From: Daniel Mason Date: Sat, 22 Apr 2023 13:34:57 +1200 Subject: [PATCH] Termiante instances that have the EBS attached --- templates/userdata.tpl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/templates/userdata.tpl b/templates/userdata.tpl index 2cbb44a..981f66a 100644 --- a/templates/userdata.tpl +++ b/templates/userdata.tpl @@ -25,6 +25,10 @@ ACC_ID=$(echo $METADATA | jq -r .accountId) device="xvdf" volume="${volume}" +# Terminate any server that already has the volume for this AZ attached +aws ec2 terminate-instances --region ${region} --instance $(aws ec2 describe-volumes --region ${region} --volume-id $volume --query 'Volumes[0].Attachments[0].InstanceId' | tr -d '"') || true + +# Attach and Mount Volume while [[ $(aws ec2 detach-volume --volume-id=$volume --region=${region}) == *"detaching"* ]]; do sleep 1; done; while [[ $(aws ec2 attach-volume --volume-id=$volume --instance-id=$(cat /etc/amazon-ec2/instance-id) --device=$device --region=${region}) == *"attaching"* ]]; do sleep 1; done;