npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

aws-ec2-wrap

v0.2.3

Published

Simplified AWS EC2 wrapper written in Node.js

Downloads

4

Readme

AWS EC2 Wrapper

NPM

Join the chat on Gitter

Build Status Coverage Status Known Vulnerabilities npm license

Simplified AWS EC2 wrapper written in Node.js, allowing you to easily work with AWS SDK for Javascript without messing around with all the parameters and restrictions.

Only some methods have been wrapped at the moment (see below on Methods), more will be implemented in the future.

Warning

I'll be implementing changes as quickly as possible, if you have a bug report or feature request, please read the Feedback section.

Please take note that this is still a beta module.

I'll ensure that patch (0.0.x) updates won't break your code, but major (x.0.0) and minor (0.x.0) ones might.

Always check this README file before upgrading to the latest version.

Latest code-breaking features

v0.1.x to v0.2.x

  • Promisified validation (check the Validation section for more info)

Changelog

Installation

To install the package, run this command inside your project's folder:

$ npm install aws-ec2-wrap --save

Credentials

Before using this module you need to setup your credentials to allow access to your AWS account.

There two ways you can do that:

  • Create a ~/.aws/credentials file to allow access that computer with the following content (replace the keys with your own):

    [default]
    aws_access_key_id=AKIAIOSFODNN7EXAMPLE
    aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

    If you already use the AWS CLI, this file should already exist.

  • Create a .env at the root of your project's folder with the following content (again replace the keys with your own):

    AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
    AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

    The dot-env module will automatically import your keys from the .env file, there's no need to install it or require it in your project.

Usage

To start using the module's methods, you need to initialize it first with your region (using the method init).

After that you can start calling any of the included methods, similar to the example below.

Once you initialized the module, you don't need to call the init method again, unless you want to change regions.

All methods return a Promise that must be handled on your side.

const EC2 = require('aws-ec2-wrap');

EC2.init('eu-west-1'); // Change to your region

EC2.getAllInstances()
    .then((instances) => {
        console.log(instances); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

Valid Regions

At the time of writing this, these are the available regions:

  • ap-northeast-1
  • ap-northeast-2
  • ap-south-1
  • ap-southeast-1
  • ap-southeast-2
  • ca-central-1
  • eu-central-1
  • eu-west-1
  • eu-west-2
  • sa-east-1
  • us-east-1
  • us-east-2
  • us-west-1
  • us-west-2

Make sure you choose the right one, or the methods might not work correctly.

Methods

In each method below you'll find the required parameters, output format, errors thrown, and usage examples.

init

Receives a region as a parameter.

Doesn't return anything.

This method initializes the connection to the AWS API for the selected region.

EC2.init('eu-west-1'); // Your region here

getAllInstances

Doesn't receive any parameter.

Returns an array of instances, where each one is the exact object returned by the AWS API.

API Reference

EC2.getAllInstances()
    .then((instances) => {
        console.log(instances); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
[
    { instance1 },
    { instance2 },
    { instance3 },
    ...
]
*/

getInstancesByStatus

Receives a status as a parameter.

Returns an array of instances that have the status provided, where each one is the exact object returned by the AWS API.

API Reference

EC2.getInstancesByStatus(status)
    .then((instances) => {
        console.log(instances); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
[
    { instance1 },
    { instance2 },
    { instance3 },
    ...
]
*/

getInstanceByIpAddress

Receives an ip address as a parameter.

Returns the instance that has the public ip address provided, or an empty object if none was found. The instance is the exact object returned by the AWS API.

API Reference

EC2.getInstanceByIpAddress(ipAddress)
    .then((instance) => {
        console.log(instance); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
{ instance }
*/

getInstanceById

Receives an instance id as a parameter.

Returns the instance that has the instance id provided, or an empty object if none was found. The instance is the exact object returned by the AWS API.

API Reference

EC2.getInstanceById(instanceId)
    .then((instance) => {
        console.log(instance); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
{ instance }
*/

getInstanceStatus

Receives an instance id as a parameter.

Returns the current status of the instance that has the instance id provided. The status is the name of the status code returned by the AWS API (InstanceState.Name).

API Reference

EC2.getInstanceStatus(instanceId)
    .then((status) => {
        console.log(status); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
'running'
*/

getInstanceIpAddress

Receives an instance id as a parameter.

Returns the public ip address of the instance that has the instance id provided. The ip address is the public ip address returned by the AWS API (PublicIpAddress).

API Reference

EC2.getInstanceIpAddress(instanceId)
    .then((ipAddress) => {
        console.log(ipAddress); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
'1.2.3.4'
*/

launchInstance

Receives the following parameters:

  • image id - the code for the AMI image to use, either a base one provided by AWS or a custom one created by you
  • instance type - the type of instance to launch (Reference)
  • key name - the key pair value used to access the instance by SSH
  • security group - the name of the security group to associate with this instance
  • tag name - the value of the Name tag to apply to this instance, as show in the Instances List on your AWS console

Returns the instance id of the newly created instance.

EC2.launchInstance(imageId, instanceType, keyName, securityGroup, tagName)
    .then((instanceId) => {
        console.log(instanceId); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
'i-0123456abc0123456'
*/

stopInstance

Receives an instance id as a parameter.

Returns a status object that contains both the previous and the current statuses of the instance, as returned by the AWS API (PreviousState.Name and CurrentState.Name).

API Reference

EC2.stopInstance(instanceId)
    .then((status) => {
        console.log(status); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
{
    previous: 'running',
    current: 'stopping'
}
*/

startInstance

Receives an instance id as a parameter.

Returns a status object that contains both the previous and the current statuses of the instance, as returned by the AWS API (PreviousState.Name and CurrentState.Name).

API Reference

EC2.startInstance(instanceId)
    .then((status) => {
        console.log(status); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
{
    previous: 'stopped',
    current: 'starting'
}
*/

terminateInstance

Receives an instance id as a parameter.

Returns a status object that contains both the previous and the current statuses of the instance, as returned by the AWS API (PreviousState.Name and CurrentState.Name).

API Reference

EC2.terminateInstance(instanceId)
    .then((status) => {
        console.log(status); // Your code here
    })
    .catch((error) => {
        console.error(error);
    });

/* Return example:
{
    previous: 'running',
    current: 'shutting-down'
}
*/

Validation

A number of validation checks are performed before the actual AWS API is called. These might throw custom errors that are provided in the module.

These custom error types and messages are exposed in EC2.errors and are described in greater detail in the Custom Errors section below.

Please check for them in your code, to ensure you are providing the correct arguments to all methods.

Handling Errors

All errors (custom and AWS ones) are now thrown inside each method's Promise (as they should be), and so they should be handled by a .catch() method in your code.

Example:

EC2.getInstanceById(instanceId)
    .then((instance) => {
        console.log(instance);
    })
    .catch((error) => {
        console.error(error); // Your error handling code here
    });

Where the error object will either be one of the custom errors or a full blown AWS API error.

Take notice that a custom error will provide its identification in the error.message property only, while an AWS API error will provide multiple properties inside the object, including the error.code and the error.message.

For example, a malformed instance id will throw an AWS API error with error.code = 'InvalidInstanceID.Malformed'. Attempting to call any method without initializing the EC2 connection with the init method will throw a custom error with error.message = EC2.errors.NOT_INITIALIZED = 'EC2 not initialized. Please call EC2.init() with a valid region.'.

Custom Errors

{
    NOT_INITIALIZED: 'EC2 not initialized. Please call EC2.init() with a valid region.',
    EMPTY_VALUE: 'Empty argument provided. Please try again with valid arguments.',
    INVALID_REGION: 'Region is invalid. Please try again with a valid region.',
    INVALID_IP: 'IP address is invalid. Please try again with a valid IPv4 address.',
    INVALID_STATUS: 'Status is invalid. Please try again with a valid status.'
}

NOT_INITIALIZED

Is thrown when you attempt to call a method without calling init before, with a valid region.

EMPTY_VALUE

Is thrown when you attempt to call a method with an empty value for a required argument.

INVALID_REGION

Is thrown when you attempt to call init with an invalid region. Check Valid Regions above.

INVALID_IP

Is thrown when you attempt to call getInstanceByIp with an invalid ip (validated by is-ip).

INVALID_STATUS

Is thrown when you attempt to call getInstancesByStatus with an invalid status.

Feedback

All bug reports and feature requests are welcome, and should be submitted through one of the following channels:

All requests will be created as Github issues, if you don't use that channel.

There are many more AWS API methods that aren't wrapped by this module. I implemented the ones that are most useful to me at the moment. I'll gladly add any that you might require on your project.

Roadmap

  • Handle valid but non-existing instance ids
  • Improve filtering on the getInstances methods (DRY)
  • Support for handling multiple instances on all methods
  • Separate code into modules
  • Add more methods (volumes, elastic ips, security groups, images, etc)
  • Support for handling large number of instances (above API limit)
  • Replace most custom errors with AWS API error handling (empty values, invalid names, etc)
  • ~~Information on setting up credentials~~
  • ~~Additional feedback channels~~
  • ~~Promisify validation and thrown errors~~
  • ~~Provide example for custom error handling~~

License

MIT © Ricardo Nunes