我想通过使用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
                            }
}

07-24 09:39
查看更多