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.sh
that publishes a CloudWatch metric namedActive
that 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.sh
on 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.ts
to setkeyName
to the name of your key - Edit
cdk-ec2-autostop-stack.ts
to uncomment the line that allows SSH connections
npm run build
compile typescript to jsnpm run watch
watch for changes and compilenpm run test
perform the jest unit testscdk deploy
deploy this stack to your default AWS account/regioncdk diff
compare deployed stack with current statecdk synth
emits the synthesized CloudFormation template