How to set EC2 instances with a specific tag to terminate automatically after a set amount of time after launch

amazon ec2amazon-web-services

We use Vagrant to launch and provision instances upon each commit to our codebase, which a continuous deployment server then runs tests against. The continuous deployment server launches the instance before running tests, but it just halts everything if one of the tests fail, and I couldn't find a way that would reliably terminate the instances in these cases.

So instead, what I'd like to do is launch the instances, tag them as temporary, and have them terminated automatically after a preset time.

  • The most obvious solution would be to schedule a shutdown when provisioning the box. I am looking for a nicer way to do this though, since we use the same Vagrantfile to provision development virtual machines, which should not shut down by themselves.
  • AWS CloudWatch can shut down instances after certain events happen (e.g. CPU idle for 30 minutes), but I couldn't find a way to apply a rule to all new instances (let alone to all new instances with a given tag.)
  • I also had a look at AWS Auto Scaling, but it wouldn't let me have zero instances active for a launch configuration.

Best Answer

An instance can terminate itself and also access its own tags. Therefore you just need to figure out how to run that from within the instance after a certain period of time if the instance has a particular tag.

You could either use a cron job, or perhaps something like monit to execute the termination if it detects your CI process isn't running for more than 5 minutes.