Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get EC2 public ip using aws-sdk Javascript

I want to get the EC2 instance's public ip using aws-sdk for Javascript. Upon executing the code below, the return gives { Reservations: [] }.

'use strict';

const AWS = require('aws-sdk');

AWS.config.loadFromPath('./aws.json');
AWS.config.update({ region: 'ap-northeast-1' });

const ec2 = new AWS.EC2({ apiVersion: '2016-11-15' });

const params = {
  Filters: [
    {
      Name: 'ip-address',
      Values: [
        'ip-address'
      ]
    }
  ],
  InstanceIds: [
    "i-0acf483a5cbdfdbeb"
  ]
};

ec2.describeInstances(params, function (err, data) {
  if (err) {
    console.log(err);
  }

  console.log(data);
});

The credentials used has been verified on IAM and is allowed access to the EC2 instance. Why can't its public ip be retrieved?

Node: 7.1.0

OS: CentOS 7.3/Windows 10

like image 994
rluisr Avatar asked Mar 11 '17 19:03

rluisr


2 Answers

I think that you don't need 'Filters' part in your params object. Use this:

const params = {
  InstanceIds: [
    "i-0acf483a5cbdfdbeb"
  ]
};

To get public ip use data.Reservations[0].Instances[0].PublicIpAddress

like image 108
Stanislav Avatar answered Nov 19 '22 18:11

Stanislav


These are all the parameters that you need:

var params = {
        Filters: [
            {
                Name: 'instance-id',
                Values: [
                    'i-0492dce5669fd6d22'
                ]
            },
        ],
    };

Documentation

like image 1
Comth Avatar answered Nov 19 '22 17:11

Comth