Search code examples
amazon-web-servicesaws-sdkamazon-ecs

Get IP address of an ECS container


I'm working from NodeJS in AWS Lambda and I'm trying to get the IP/hostname of a particular container in my ECS cluster. ELB is out of the question for us or I'd just use that.

This is what I came up with:

const AWS = require('aws-sdk');
const ecs = new AWS.ECS({region: 'us-east-1'});
const ec2 = new AWS.EC2({region: 'us-east-1'});

const CLUSTER = 'MyClusterNameHere';


function getIP() {
  return ecs.listContainerInstances({ cluster: CLUSTER }).promise()
    .then(data => ecs.describeContainerInstances({ containerInstances: data.containerInstanceArns, cluster: CLUSTER }).promise())
    .then(data => ec2.describeInstances({ InstanceIds: [ data.containerInstances[0].ec2InstanceID ] }).promise())
    .then(data => data.Reservations[0].Instances[0].PrivateDnsName);
}

getIP().then(data => console.log(data))

This seems like an awful lot of API calls and a lot of burrowing into complex objects just to get what I want. I'd love a faster, less intense way to get this.

NB: I can use Instances[0] here even though I shouldn't because I know there's only one container and only ever one instance but the IP may change sporadically


Solution

  • I wasn't able to find a faster way so I just went with what I had.