Skip to content

Instantly share code, notes, and snippets.

@Angelin01
Created November 29, 2021 13:09
Show Gist options
  • Save Angelin01/a8152be001792299e1f26a82adfa3989 to your computer and use it in GitHub Desktop.
Save Angelin01/a8152be001792299e1f26a82adfa3989 to your computer and use it in GitHub Desktop.
AWS EC2 Spot Instance Interrupt Monitor for Graceful Stop
#!/bin/bash
set -o nounset -o pipefail
IMDS_ENDPOINT=${IMDS_ENDPOINT:-"http://169.254.169.254"}
IMDS_VERSION=${IMDS_VERSION:-latest}
MONITOR_INTERVAL=${MONITOR_INTERVAL:-5}
check_dependencies() {
local dependencies=("jq" "curl")
local err=false
for executable in "${dependencies[@]}"; do
if ! command -v "$executable" > /dev/null; then
printf "ERROR: Executable '%s' is required, but I could not find it.\n" "$executable" >&2
err=true
fi
done
if "$err"; then
printf "Install the missing dependencies and make sure they are available on your PATH.\n" >&2
printf "I checked using 'command -v EXECUTABLE'.\n" >&2
exit 1
fi
}
get_metadata() {
local path=$1
local token_ttl=15
local token
token=$(curl -sS -X PUT "$IMDS_ENDPOINT/$IMDS_VERSION/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: $token_ttl")
curl -sSf -H "X-aws-ec2-metadata-token: $token" "$IMDS_ENDPOINT/$IMDS_VERSION/meta-data/$path" 2> /dev/null
}
should_terminate() {
local response=$1
local action
if action=$(echo "$response" | jq -r ".action") && [ "$action" = "terminate" ]; then
return 0
fi
return 1
}
monitor_interrupt() {
printf "Monitoring for interruption notice\n"
local response
until response=$(get_metadata "spot/instance-action") && should_terminate "$response"; do
sleep "$MONITOR_INTERVAL"
done
printf "Received termination notice!\n"
}
graceful_stop() {
# =======================================
# Code to perform graceful stop goes here
# =======================================
}
check_dependencies
monitor_interrupt
graceful_stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment