Skip to content

Commit

Permalink
Added EC2 termination notice script handler
Browse files Browse the repository at this point in the history
  • Loading branch information
rennokki committed Dec 9, 2020
1 parent f41f0c1 commit 4031160
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
20 changes: 19 additions & 1 deletion .platform/files/supervisor.ini
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@
# user=root
# numprocs=1
# redirect_stderr=true
# stdout_logfile=/var/log/supervisor.log
# stdout_logfile=/var/log/laravel-worker.log
# stopsignal=INT
# stopwaitsecs=60

# Uncomment the following process to enable
# EC2 spot termination notices.

# [program:ec2-spot-termination-notice]
# process_name=%(program_name)s_%(process_num)02d
# command=sh spot-termination.sh
# directory=/var/app/current/.platform/scripts
# autostart=true
# autorestart=true
# killasgroup=true
# stopasgroup=true
# user=root
# numprocs=1
# redirect_stderr=true
# stdout_logfile=/var/log/supervisor-ec2-interruption-notice.log
# stopsignal=INT
# stopwaitsecs=60
36 changes: 36 additions & 0 deletions .platform/scripts/spot-termination.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/bin/bash

# Spot Termination notice handler.
# See https://aws.amazon.com/blogs/compute/best-practices-for-handling-ec2-spot-instance-interruptions/

# If you are using spot instances, you might want to handle termination notices.
# This script will continuously poll the EC2 Metadata Endpoint every 5 seconds,
# and if it detects a termination notice, it can run your arbitrary code, like safely
# shutting down processes, for example.

# To active this script, you shall uncomment the .platform/files/supervisor.ini process
# that will keep this script alive throughout the instance lifecycle until its termination.

TOKEN=`curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`

while sleep 5; do

HTTP_CODE=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s -w %{http_code} -o /dev/null http://169.254.169.254/latest/meta-data/spot/instance-action)

if [[ "$HTTP_CODE" -eq 401 ]] ; then

# Refreshing the authentication token...
TOKEN=`curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 30"`

elif [[ "$HTTP_CODE" -eq 200 ]] ; then

# Here, the instance knows it will be interrupted.
# Run your code.

else

# Here, the instance is not interrupted.

fi

done
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ $ chmod +x .platform/hooks/predeploy/*.sh
$ chmod +x .platform/hooks/postdeploy/*.sh
```

```bash
$ chmod +x .platform/scripts/*.sh
```

# AWS EB Should-Know

## Deployment Stages
Expand Down

0 comments on commit 4031160

Please sign in to comment.