Get AWS ELB name from an attached instance

amazon ec2amazon-elbamazon-web-servicesload balancing

I created one ELB and attached a few instances to this ELB. So when I login into one of these attached instance, I would like to type a command or run a nodejs script that can return me the its ELB name. Is it possible? I know I can look up on AWS console but I'm looking for a way to look it up programmatically. If possible, I would like to see how it is done in either command or AWS Nodejs SDK.

Thanks!

Best Answer

I'm not the greatest in JavaScript but I tested the code below and works. It basically uses the "describeLoadBalancers" API call to get a list of all your ELBs and then iterates through the result to look for your instance. If your instance is registered with a particular load balancer, it's name is output to the console:

// Require AWS SDK for Javascript
var AWS = require('aws-sdk');

// Set API Keys and Region
AWS.config.update({
    "accessKeyId": "<your access key>", 
    "secretAccessKey": "<your secret key>",
    "region": "us-west-1" // specify your region
});

// Get All Load Balancers
function GetLoadBalancers(fn)
{
    var elb = new AWS.ELB();
    elb.describeLoadBalancers(null,function(err, data) {
        fn(data)
    });
}

// Loop through response to check if ELB contains myInstanceId
var myInstanceId = "<your instance id>";
GetLoadBalancers(function(elbs){
    elbs.LoadBalancerDescriptions.forEach(function(elb){
      if(elb.Instances[0] != undefined){
        if (elb.Instances[0].InstanceId == myInstanceId){
            console.log(elb.LoadBalancerName);
        }
      }
    });
});