pythonamazon-web-servicescommand-line-interfacespot-instances

What Python or CLI call can I use to terminate an AWS spot instance and request from within the spot instance itself?


I have a long running aws job and am using spot instances (single-instance per job) to save money. The python code can handle the stopping and restarting, but when I come to the end of the analysis work, I want to terminate the spot instance and not launch any more (for that batch) so that I don't have to babysit things manually (I'm using expensive GPU instances so I want to stop as soon as possible). My code is all in python - is there an aws python sdk or cli call that will terminate that spot instance and stop any more from being launched, all from within the spot instance itself? The upshot is I don't want to pay for GPU time once my work is finished.

A related question from several years ago is here, but it didn't fully answer my question.

thank you!


Solution

  • Perform following actions on the last spot instance:

    1. Retrieve instance ID: wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
    2. Modiy the instance's shutown behavior: aws ec2 modify-instance-attribute --instance-initiated-shutdown-behavior terminate
    3. Then when you want to terminate it: sudo shutdown -h now. Shutdown can also be scheduled by: echo "sudo halt" | at now + 5 minutes.