2016-08-11 69 views
1

我一直在node中使用AWS JS SDK,並且我想描述所有地區的現有ec2 istances,但我得到一個空的reservation[]。我試圖用 AWS.config.update{}指定一個區域,它按預期工作,它返回實例,但這是我想要的。我想查詢AWS的所有實例,而不指定區域。有一個簡單的方法!? (我用我的智能手機問這個問題,我現在無法訪問我的電腦)。在節點中使用AWS JS SDK來描述所有ec2實例

謝謝你的幫助。

回答

1

您必須遍歷每個區域,併爲每個區域調用一次。 API是區域特定的,您無法在單個API調用中獲取所有區域中的所有EC2實例的列表。

1

根據Amazon Web Services docs

例如,如果需要訪問多個 區域亞馬遜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)); 
 
    } 
 
}

OUTPUT:

[{"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":[]}] 

我切斷了我使用的,因爲它是很長的區域輸出。