在节点中使用AWS JS SDK来描述所有ec2实例

时间:2016-08-11 23:52:09

标签: node.js amazon-ec2 aws-sdk

我一直在AWS JS SDK使用node,我想在所有地区描述我现有的ec2点,但我得到一个空的reservation[]。我尝试使用指定区域 AWS.config.update{}它按预期工作,它返回实例,但这就是我想要的。我想查询AWS我的所有实例,而不指定区域。有一个简单的方法!? (我用我的智能手机提出这个问题,我现在无法访问我的电脑)。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

根据Amazon Web Services docs

  

例如,如果您需要多个访问Amazon EC2对象   区域,为每个区域创建一个EC2服务对象,然后设置   因此,每个服务对象的区域配置。

var ec2_regionA = new AWS.EC2({region: 'ap-southeast-2', maxRetries: 15, apiVersion: '2014-10-01'});
var ec2_regionB = new AWS.EC2({region: 'us-east-1', maxRetries: 15, apiVersion: '2014-10-01'});

我的实施,



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

var EC2Objects = [
    new AWS.EC2({apiVersion: '2016-11-15',region: 'us-east-1'}),      //N. Virginia
    new AWS.EC2({apiVersion: '2016-11-15',region: 'us-east-2'}),      //Ohio
    new AWS.EC2({apiVersion: '2016-11-15',region: 'us-west-1'}),      //N. California
    new AWS.EC2({apiVersion: '2016-11-15',region: 'us-west-2'}),      //Oregon
    new AWS.EC2({apiVersion: '2016-11-15',region: 'ca-central-1'}),   //Canada (Central)
    new AWS.EC2({apiVersion: '2016-11-15',region: 'eu-west-1'}),      //Ireland
    new AWS.EC2({apiVersion: '2016-11-15',region: 'eu-central-1'}),   //Frankfurt
    new AWS.EC2({apiVersion: '2016-11-15',region: 'eu-west-2'}),      //London
    new AWS.EC2({apiVersion: '2016-11-15',region: 'ap-northeast-1'}), //Tokyo
    new AWS.EC2({apiVersion: '2016-11-15',region: 'ap-northeast-2'}), //Seoul
    new AWS.EC2({apiVersion: '2016-11-15',region: 'ap-southeast-1'}), //Singapore
    new AWS.EC2({apiVersion: '2016-11-15',region: 'ap-southeast-2'}), //Syndney
    new AWS.EC2({apiVersion: '2016-11-15',region: 'ap-south-1'}),     //Mumbai
    new AWS.EC2({apiVersion: '2016-11-15',region: 'sa-east-1'})       //Sao Paulo
];

var instances = [];
listEc2();

function listEc2(){
    var params = {};
    for(var i=0; i<EC2Objects.length; i++){
        EC2Objects[i].describeInstances(params, function(err, data) {
            if (err) console.log(err, err.stack); // an error occurred
            else     ec2ListBuilderCallback(data);           // successful response
        });
    }
}

function ec2ListBuilderCallback(data){
    instances.push(data); 
    if(instances.length == EC2Objects.length){
        console.log(JSON.stringify(instances));
    }
}
&#13;
&#13;
&#13;

输出:

[{"Reservations":[]},{"Reservations":[{"ReservationId":"r-0e7c0a2e3cf30944c","Groups":[],"Instances":[{"InstanceId":"i-0391f0e44b04675ad","ImageId":"ami-0b33d91d","State":{"Code":16,"Name":"running"}],{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]},{"Reservations":[]}]

我切断了我正在使用的区域的输出,因为它真的很长。

答案 1 :(得分:1)

您必须遍历每个区域,并为每个区域拨打一次电话。 API是特定于区域的,您无法在单个API调用中获取所有区域中所有EC2实例的列表。