Hi, our company uses a lot of aws instances (spots & on demand) for integration tests, unit tests, staging etc.. i would like to hear about a solution / automation process who terminate unused instances. I thought maybe to tag them with an expiration date and then running script to delete the expired instances. suggestions?
Thanks!
IMO This is highly dependent on your workflow. For short-lived job instances, I just integrate the startup and shutdown of the instances within the Jenkins job itself.
Depends on how you would programmatically determine that an instance is “unused.”
If you’re spinning up an instance through a CI/CD pipeline to run some tests, and you know that you want the instance to terminate after those tests, just build that into your Jenkins jobs or whatever.
Or if you’re determining “unused” by some metric like CPU usage, autoscaling groups fit this exact use case.
If you have any sort of automation in process that can bring the instances in the state you want them to, I would just put that in the user-data and use AWS::AutoScaling::ScheduledAction. We take the test environments down later in the evening and they’re being brought up in the morning before the devs come in.
First, not best thought:
One option that would be a sledgehammer approach would be to create instances that have a specific key/value tag and then create an IAM user that only has the ability to terminate instances with the same tag pair. Then use that IAM user to run a Lambda on a schedule to terminate all instances in a “Stopped” state.
If the IAM policy of the user is modified or tags are inappropriately, you run a risk of incorrectly terminating. If you are already using spot instances, I’m assuming the workload is recovery friendly.
This is NOT a solution, but first thoughts.
I manage an entirely spot instance fleet that has no fundamental uptime requirements. I hacked together a script that checks for logged in users and system load, and run it using systemd timers.
Cloud Custodian is a useful tool that has enough features to implement a flexible set of policies to manage resources. You can use it to implement the policy you describe, or other policies as well.