Last active
August 11, 2022 16:54
-
-
Save pahud/002ae4652a4609ca21f8f95d7ee8dee1 to your computer and use it in GitHub Desktop.
EC2 spot instance terminating notify
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 | |
az=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone) | |
region=${az%%?} | |
instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id) | |
logfile='/tmp/termination-time.out' | |
sns_arn=${ARN-undefined_arn} | |
sns_subject=${SUBJECT-"spot instance is terminating"} | |
message="{\"instanceId\": \"${instance_id}\", \"region\":\"${region}\"}" | |
polling() { | |
http_code=$(curl -s http://169.254.169.254/latest/meta-data/spot/termination-time -w "%{http_code}\n" -o $logfile) | |
if [[ $http_code != "404" ]]; then | |
return 0 | |
else | |
return 1 | |
fi | |
return false | |
} | |
notify() { | |
echo "spot instanceId: ${instance_id} in region: ${region} is terminating now" | |
aws sns --region $region publish --subject "$subject" --message "$message" --topic-arn $sns_arn | |
} | |
while true | |
do | |
polling && echo "got signal" && cat $logfile && notify && break | |
sleep 5 | |
done | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment