An AWS CLI / Node.js Script for Terminating EC2 Instances

The AWS Command Line Interface (CLI) is a powerful scripting platform written in Python that uses the AWS Cloud's RESTful management API for performing various operational tasks, like creating S3 buckets, deleting EBS volumes, etc.In this blog, I will show you how you can terminate EC2 instances from your local computer using AWS CLI wrapped up as a Node.js app.

What you need is these four things:

Have an account with AWS (a credit card will be required if you don’t have one)

Have AWS CLI installed on your favorite OS. I used Windows and followed the AWS CLI installation instructions
Mind you, that as of March 2017 the MSI installer for the AWS CLI does not work with Windows Server 2008 (version 6.0.6002). Use Python's package manager, pip, to install with this version of Windows.

Have the aws Universal Command Line Environment (tool) configured with your account credentials for remote access:

AWS Access Key ID, and

AWS Secret Access Key

The communication between your local computer and AWS is done over SSL, so you have an effective point-to-point encrypted channel.

I do not describe the configuration steps, which you can find on the AWS web site.

When you run the aws tool for the first time, you will be prompted with a Firewall Alert -- just select the Allow Always (or something along those lines) rule for it.

Have Node.js installed on your computer.While you may achieve quite a lot with simple AWS CLI scripts, its real power can be unleashed by creating small Node.js utility apps scripted around the raw AWS CLI.

I use the terms Node.js app and script interchangeably.

As an option, you can install AWS SDK for JavaScript in Node.js, but then you will need to learn the SDK.

Note: While request for termination is enqueued right away, the EC2 service may take quite some times (like hours) to actually remove the terminated instances.

Here is the code for a Node.js app that terminates (stops and deletes) EC2 instances. I used Visual Studio Code IDE for developing and debugging the script.