shutdown/startup 基于标签 lambda 函数的 ec2 实例不工作

shutdown/startup ec2 instances based on tag lambda function not working

我想 start/stop 使用 lambda 函数基于单个标签和值的 ec2 实例。

我正在尝试改编一些代码:https://github.com/SamVerschueren/aws-lambda-stop-server

到目前为止,我已经能够指定我想要 运行 lambda 函数针对的区域,但无法锻炼如何过滤实例。即过滤带有标签 "schedule" 的实例,然后对值进行拆分字符串并检查是否有一个拆分值匹配 "stop6pmdaily"。例如 schedule=start8amdaily|stop6pmdaily

if (instance.State.Code === 16) {
// 0: pending, 16: running, 32: shutting-down, 48: terminated, 64: stopping, 80: stopped
    values = instance.Tags["schedule"].Value.Split("|")
    for (v of values) {
        if (v == 'stop6pmdaily'){
            stopParams.InstanceIds.push(instance.InstanceId);
        }
    }
}

所以完整的功能代码如下:

'use strict';

/**
 * AWS Lambda function that stops servers.
 *
 * @author Sam Verschueren      <sam.verschueren@gmail.com>
 * @since  09 Oct. 2015
 */

// module dependencies
var AWS = require('aws-sdk');
 AWS.config.update({region: 'ap-southeast-2'});
var pify = require('pify');
var Promise = require('pinkie-promise');

var ec2 = new AWS.EC2();

/**
 * The handler function.
 *
 * @param {object}  event  The data regarding the event.
 * @param {object}  context  The AWS Lambda execution context.
 */
exports.handler = function (event, context) {

 // Describe the instances
 pify(ec2.describeInstances.bind(ec2), Promise)() //(describeParams)
  .then(function (data) {
   var stopParams = {
    InstanceIds: []
   };

   data.Reservations.forEach(function (reservation) {
    reservation.Instances.forEach(function (instance) {
     if (instance.State.Code === 16) {
      // 0: pending, 16: running, 32: shutting-down, 48: terminated, 64: stopping, 80: stopped
      values = instance.Tags["schedule"].Value.Split("|")
      for (v of values) {
       if (v == 'stop6pmdaily'){
        stopParams.InstanceIds.push(instance.InstanceId);
       }
      }
     }
    });
   });

   if (stopParams.InstanceIds.length > 0) {
    // Stop the instances
    return pify(ec2.stopInstances.bind(ec2), Promise)(stopParams);
   }
  })
  .then(context.succeed)
  .catch(context.fail);
};

原来我没有正确访问标签数组。

instance.Tags.forEach(function (Tag) {
                            if (Tag.Key == 'schedule') {
                            //do something
                            }
}