Tuesday, June 4, 2024

AWS Instance that's SSM Manageable and terminates itself after an hour

A common problem is that you create an instance to do some testing, and then forget about it and it ends up costing for no reason....


Here is some Terraform code that:

  • creates the instance
  • creates instance role, with SSM (AmazonSSMFullAccess) so you can use session manager to get to it
  • sets an EC2 termination policy so you can terminate it from within (this was version 1)
  • creates a user through user-data so you can use EC2 Serial Console to log into it if needed
  • makes sure the AWS SSM Agent is installed. 
  • Sets it to terminate upon stop, changes the  "shutdown behavior" to terminate (see pic below)  

edit main.tf, line 160, and change the time you want the instance to terminate here are some examples:

0 * * * * every hour (the default)
0 0 * * *  every day at 12am (this would be UTC usually)

You can use something like https://crontab.cronhub.io/  to tailor the time. 

To use it, simply put the VPC and Subnet you want it on, and run 

# terraform init 
# terraform apply


Enjoy!