问题原文
原帖链接 · Nam Nguyen · CC BY-SA 3.0
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!
已采纳解答
原帖链接 · Ameer Deen · CC BY-SA 4.0
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);
}
}
});
});
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
