如何在AWS中获取实例的名称标签?

时间:2016-08-16 20:01:56

标签: node.js amazon-web-services amazon-ec2

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

var getLatestProducts = function() {
  var dfd = new $.Deferred();
  var productIds = [];
  var products = [];

  for (var i in cart.contents) {
    productIds.push(cart.contents[i].id);
  }

  var promises = $.map(productIds, function(productId, idx) {
      return moltin.Product.Get(productId, function(product) {
          products.push(product);
      });
  }
  $.when.apply($, promises).then(function() {
      dfd.resolve(products);
  }
  return dfd.promise();
};

var promise = getLatestProducts();

promise.done(function(result) {
  var products = result;

  products.forEach(function(product) {
    // products should be an array of all products that were in the cart
    // now filter those you want (stock level etc.)
    // and do awesome stuff
  });
}

以下是我得到的结果:

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);                            
                    }
                }
            });

1 个答案:

答案 0 :(得分: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);
                            });                                
                          }
                        }
                    }
                }
            });