Bootstrap FreeKB - Amazon Web Services (AWS) - List EC2 Instances using Node.js
Amazon Web Services (AWS) - List EC2 Instances using Node.js

Updated:   |  Amazon Web Services (AWS) articles

This assumes you are familiar with the basic configurations needed to connect to Amazon Web Services (AWS) using NodeJS. If not, check out my article Getting Started with NodeJS aws-sdk.

The @aws-sdk/client-ec2 package is used to interact with AWS EC2 in NodeJS. The npm list command can be used to determine if you have the @aws-sdk/client-ec2 package installed. If not, the npm install command can be used to install the package. Once installed, your package.json should include the @aws-sdk/client-ec2 package.

{
  "dependencies": {
    "@aws-sdk/client-ec2": "^3.606.0"
  }
}

 

Here is the minimal boilerplate code without any error handling to list your EC2 Instances using CommonJS.

const { EC2Client, DescribeInstancesCommand } = require("@aws-sdk/client-ec2");
const client = new EC2Client({ region: "us-east-1" });
const params = {};
const command = new DescribeInstancesCommand(params);

async function myInstances() {
  return await client.send(command);
}

myInstances()
  .then(response => {console.log(response)})
  .catch(err => {console.error(err)});

 

If your app is an ES module, package.json will have "type": "module".

{
  "type":"module",
  "dependencies": {
    "@aws-sdk/client-ec2": "^3.620.0"
  }
}

 

In this scenario, you will use import instead of require.

import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2";

 

Which should return something like this.

{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'c8dcff88-3644-4567-b966-ad1f9a9d0dae',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  Reservations: [
    {
      Groups: [],
      Instances: [Array],
      OwnerId: '123456789012',
      ReservationId: 'r-0212311abcd68a700'
    },
    {
      Groups: [],
      Instances: [Array],
      OwnerId: '123456789012',
      ReservationId: 'r-0fabcd0c203d31234'
    }
  ]
}

 

Here is how you can list each EC2 instance.

import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2";
const client = new EC2Client({ region: "us-east-1" });
const params = {}
const command = new DescribeInstancesCommand(params);
const response = await client.send(command);

if (response.Reservations.length == 0 ) {
  console.error(`no EC2 instances found`);
  process.exit(1)
} else {
  response.Reservations.forEach(item => {
    console.log(item)
  })
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 3cbf20 in the box below so that we can be sure you are a human.