2016-08-16 119 views
0

使用此代码,我可以列出所有实例的第一个插槽中的所有标记。但我想要做的是获取每个实例的名称标签并将其存储在一个数组中。如何获取AWS中实例的名称标签?

ec2.describeInstances(function(err, result) { 
       if (err) 
        console.log(err); 
       var inst_id = '-'; 
       for (var i = 0; i < result.Reservations.length; i++) { 
        var res = result.Reservations[i]; 
        var instances = res.Instances; 
        for (var j = 0; j < instances.length; j++) { 
         var tagArr = instances[j].Tags[0]; 

         console.log(tagArr);        
        } 
       } 
      }); 

下面是结果我得到:

{ Key: 'Name', Value: 'name1' } 
{ Key: 'Name', Value: 'name2' } 
{ Key: 'Name', Value: 'name3' } 
{ Key: 'MigrationDate', Value: '2016-07-03' } 
{ Key: 'Billing', Value: 'Bill' } 
{ Key: 'Name', Value: 'name4' } 

回答

1

我能解决我自己的问题。 :)

ec2.describeInstances(function(err, result) { 
       if (err) 
        console.log(err); // Logs error message. 
       var inst_id = '-'; 
       for (var i = 0; i < result.Reservations.length; i++) { 
        var res = result.Reservations[i]; 
        var instances = res.Instances; 
        for (var j = 0; j < instances.length; j++) { 
         var instanceID = instances[j].InstanceId; 
         var tags = instances[j].Tags; 
         for (var k = 0; k < tags.length; k++) { 
          if (tags[k].Key == 'Name') { 
          var params = { 
           InstanceId: instanceID, /* required */ 
           Name: tags[k].Value, /* required */ 
           Description: 'Testing AMI Node3', 
           DryRun: false, 
           NoReboot: true 
          }; 
          ec2.createImage(params, function(err, data) { 
           if (err) console.log(err, err.stack); 
           else  console.log(data); 
          });         
          } 
         } 
        } 
       } 
      }); 
相关问题