LoginSignup
3
5

More than 5 years have passed since last update.

EC2スポットインスタンスの停止を検知

Posted at

EC2のスポットインスタンスは激安でとても有り難いのですが、時々相場が跳ね上がって突然terminateされてしまうのが難点です。
ですが、以下の方法で、terminateされる約2分前にそれを検知することが出来ますので、データの保全や代わりのインスタンスを起動するなどの対処が可能です。

手順

スポットインスタンス上に/home/ec2-user/ec2_termination_detector.shというパスで以下のファイルを作成します。

#!/bin/bash

while true
  do
    if [ -z $(curl -Is http://169.254.169.254/latest/meta-data/spot/termination-time | head -1 | grep 404 | cut -d \  -f 2) ]
      then
        # もうすぐ停止するので何かしら準備します

        # とりあえずメールする例
        echo "さよなら〜" | mail -s "死ぬ〜" -r from@example.com to@example.com
        break
      else
        sleep 5
    fi
  done

このスクリプトは5秒間隔でterminateされそうになってないかチェックします。

chmod 744 /home/ec2-user/ec2_termination_detector.shで実行権限を付与したら、以下の様にバックグラウンドで動かします。

/home/ec2-user/ec2_termination_detector.sh > /dev/null 2>&1 &
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5