Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Stop AWS EC2 in case of inactivity

Can we stop an AWS windows server EC2 instance of a development environment when there is no activity in it, say after 2 hours of inactivity? I am having trouble identifying whether any user is connected to the server virtually.

I can easily start/stop the EC2 at a fixed time, programmatically, but in order to cut the cost of my server, I am trying to stop the EC2 when it is not being used.

My intent(or use case) is: If no user is using the EC2 till a specified amount of time, it will automatically stop. Developers can restart it as and when needed.

like image 444
NG. Avatar asked Jul 30 '20 05:07

NG.


People also ask

How do you stop an EC2 instance when not in use?

To get started, first visit Amazon EC2 in the AWS Management Console, select an instance, and click the 'Create Alarm' button in the Monitoring tab that appears in the lower panel. Then, enter an email address to notify, choose 'Stop' or 'Terminate', set a utilization threshold that suits your needs, and you're done.

Can EC2 instance stop itself?

If you want to assign it as Self-Stopping on Self-Terminating, you can do it one time only. In your EC2 Console go to Instance Settings, change Shutdown Behavior to Stop.


1 Answers

Easiest solution probably would be to set up an Alert with CloudWatch.

Have a read at the documentation, which basically describes your use case perfectly:

You can create an alarm that stops an Amazon EC2 instance when a certain threshold has been met

A condition could be the average CPU utilisation, e.g. CPU utilisation is below a certain point (which most probably correlates with no logged in users / no developer actually utilising the machine).

like image 112
tpschmidt Avatar answered Nov 08 '22 12:11

tpschmidt