Shell script to boot up, connect, and shutdown AWS instances, all automatically!

If you’re like me, you always forget to shut down your AWS instance. I created a small script that allows easy connection to multiple AWS instances based on command line arguments, and automatically shuts the instance down when you disconnect from the AWS session.

Features:

  • Automatically port forwards to allow easy Jupyter notebook connection — just go to localhost:8888!
  • Tracks the time spent in the current session and prints it to the terminal when you log off the AWS instance
  • Automatically shuts the AWS instance down when you log off
  • Choose from as many different instances as you like via customizeable command line arguments (example below)
  • Automatically logs in with the correct user based on the instance
  • Automatically determines the IP of the instance if it changes, so you don’t need to pay Amazon for a static IP!

Example:

$ ./ssh-into-aws.sh p2
Booting up the instance...
STARTINGINSTANCES       i-016940554988ae126
CURRENTSTATE    0       pending
PREVIOUSSTATE   80      stopped
Waiting a few seconds to ensure full startup...
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-1052-aws x86_64)
(fastai) ubuntu@ip-172-31-37-237:~$ 

In this case, p2 is the command line argument that I’ve provided the script, so it automatically boots up my P2 instance, determines the IP, SSHes in, and I can get to work!

When I log off:

(fastai) ubuntu@ip-172-31-37-237:~/fastai$ exit
logout
Connection to 54.202.254.240 closed.
STOPPINGINSTANCES       i-016940554988ae126
CURRENTSTATE    64      stopping
PREVIOUSSTATE   16      running
Time Elapsed: 11 Minutes

There’s instructions to modify the script for your own use in the code — post here if you have questions!

Get it here: https://github.com/thedch/bash-scripts/blob/master/ssh-into-aws.sh

You’ll also need the AWS CLI on your local machine, which you can get here: https://aws.amazon.com/cli/

Can’t wait to meet you all tomorrow!

14 Likes