Self-Terminating AWS EC2 Instance?

Steve3p0 picture Steve3p0 · May 10, 2012 · Viewed 34.3k times · Source

Is there a way that Amazon Web Services EC2 instances can be self terminating? Does Amazon have anything that allows an instance to terminate itself ("Hara-Kiri") after running for more than say an hour? I could change the scripts on the running instance to do this itself, but that might fail and I don't want to edit the image, so I would like Amazon to kill the instance.

Answer

Eric Hammond picture Eric Hammond · May 10, 2012

To have an instance terminate itself do both of these steps:

  1. Start the instance with --instance-initiated-shutdown-behavior terminate or the equivalent on the AWS console or API call.
  2. Run shutdown -h now as root. On Ubuntu, you could set this up to happen in 55 minutes using:

    echo "sudo halt" | at now + 55 minutes
    

I wrote an article a while back on other options to accomplish this same "terminate in an hour" goal:

Automatic Termination of Temporary Instances on Amazon EC2
http://alestic.com/2010/09/ec2-instance-termination

The article was originally written before instance-initiated-shutdown-behavior was available, but you'll find updates and other gems in the comments.