#!/bin/bash set -ex # This script monitors the lifecycle state of the current AWS EC2 instance and triggers # a termination script when the instance state is set to "Terminated". # The script uses the AWS Instance Metadata Service (IMDS) to determine the state of the instance. # The termination script to be triggered and the termination message are read from a config JSON file. # The script expects a grace period in minutes as an argument, which it passes to the termination script. # The script runs in an infinite loop, checking the instance state every 60 seconds. # # This script must be executed as <%= node['cluster']['cluster_admin_user'] %> because # because only this user has sudoers privileges to execute the termination hook. CONFIG_PATH="<%= node['cluster']['shared_dir_login_nodes'] %>/loginmgtd_config.json" CONFIG_JSON=$(cat $CONFIG_PATH) TERMINATION_SCRIPT_PATH=$(echo $CONFIG_JSON | jq -r .termination_script_path) TERMINATION_MESSAGE=$(echo $CONFIG_JSON | jq -r .termination_message) GRACETIME_PERIOD=$(echo $CONFIG_JSON | jq -r .gracetime_period) DAEMON_SLEEP_SECONDS=60 IMDS_ENDPOINT="http://169.254.169.254" while true; do IMDS_TOKEN=$(curl -X PUT "$IMDS_ENDPOINT/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 3600") INSTANCE_LIFECYCLE_STATE=$(curl -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" -v "$IMDS_ENDPOINT/latest/meta-data/autoscaling/target-lifecycle-state") if [[ "$INSTANCE_LIFECYCLE_STATE" == "Terminated" ]]; then break fi sleep $DAEMON_SLEEP_SECONDS done sudo "$TERMINATION_SCRIPT_PATH" "$TERMINATION_MESSAGE" "$GRACETIME_PERIOD"