This project demonstrates how to use the CDK to create an EC2 instance that automatically stops when there are no more active SSH or Session Manager connections to it. This can be useful for an instance that is only used occasionally to remotely access an RDS cluster.
When you deploy this stack and EC2 instance is provisioned that automatically stops after running for about 15-30 minutes without an SSH or Session Manager connection. It can be manually re-started at any time and will again be automatically stopped after running for about 15-30 minutes without an SSH or Session Manager connection.
This project implements the following solution:
-
Install a bash script
report-metrics.shthat publishes a CloudWatch metric namedActivethat indicates whether the current instance is "active" or not. We consider an instance to be active if it has any incoming SSH or Session Manager connections or if it was recently booted. -
Configure a cronjob to run
report-metrics.shon the instance once a minute. -
Configure a CloudWatch Alarm that stops the instance once it remains inactive over a 15 minute period.
NOTES:
- As currently implemented you can only use Session Manager to connect to this instance.
- If you want to connect directly with SSH you must do the following:
- Create an EC2 Key Pair
- Edit
cdk-ec2-autostop-stack.tsto setkeyNameto the name of your key - Edit
cdk-ec2-autostop-stack.tsto uncomment the line that allows SSH connections
npm run buildcompile typescript to jsnpm run watchwatch for changes and compilenpm run testperform the jest unit testscdk deploydeploy this stack to your default AWS account/regioncdk diffcompare deployed stack with current statecdk synthemits the synthesized CloudFormation template