Node js中箭头函数array/json输出的键值对返回值



我有一个用JavaScript编写的箭头函数,在Node.js中运行,它根据AWS中的EC2实例id获取EC2实例信息。在我看来,在下面的函数中,InstanceIds是在创建实例时从CloudTrail事件传递进来的参数。

const AWS = require('aws-sdk');
exports.handler = async (event) => {
/** find instance Operating System for OS tag */
var instances = await Promise.all(event.detail.responseElements.instancesSet.items.map(x => getInstanceInfo({ InstanceIds: [x.instanceId] })));
var newTags = [];
/** 
*if (event.detail.userIdentity.type === 'Root') {
*    newTags.push({ Key: 'Owner', Value: 'Root' });
*} else {
*    newTags.push({ Key: 'Owner', Value: event.detail.userIdentity.arn.split('/').pop() });
*};
*/
newTags.push({ Key: 'Created', Value: event.detail.eventTime });
//newTags.push({ Key: 'OS', Value: instanceos });
//newTags.push({ Key: 'ImageId', Value: instance.OS });
/** handling our logic specific to ec2 and run instances. We can add in other logic here */
if (event.source === 'aws.ec2' && event.detail.eventName === 'RunInstances') {
/** calling the update function for each instance */
var instances = await Promise.all(event.detail.responseElements.instancesSet.items.map(x => getInstanceInfo({ InstanceIds: [x.instanceId] })));

/** calling the update function for each instance */
await Promise.all(instances.map(x => ec2Update(x, newTags)));
} else if (event.source === '') {
// place logic for other service here!
}
//console.log(instanceos)
return "tags have been set!";
};
var ec2Update = (instance, tags) => new Promise(async (resolve) => {
/** creating a new list of myTags since they are unique to this instance */
var myTags = JSON.parse(JSON.stringify(tags));
/** setting tag keys that we want to ignore and setting all to lowercase */
var ignoreKeysLowerCase = ['name','aws:cloudformation:stack-name','aws:cloudformation:stack-id','aws:cloudformation:logical-id'];
/** Getting the tags from the VPC to pass onto the instance */
var vpc = await getVpc({ VpcIds: [instance.VpcId] });
/** Getting Ignoring keys that we do not want to passed to the instance */
vpc.Tags.map(x => { if (!ignoreKeysLowerCase.includes(x.Key.toLowerCase())) { myTags.push(x) } });
/** Getting Ignoring keys that we do not want to passed to the instance */
await setTags(instance.InstanceId, myTags);
resolve();
});
var InstanceIds = (params) => new Promise((resolve) => {
console.log(params)
var aws = new AWS.EC2({ region: process.env.AWS_REGION }).describeInstances(params);
aws.on('success', r => {
resolve(r.data.Reservations[0].Instances[0]);
}).on('error', e => {
console.log('error in describeInstances', e.message);
}).send();
});
var getVpc = (params) => new Promise((resolve) => {
var aws = new AWS.EC2({ region: process.env.AWS_REGION }).describeVpcs(params);
aws.on('success', r => {
resolve(r.data.Vpcs[0])
}).on('error', e => {
console.log('error in describeVpcs', e.message);
}).send();
});
var setTags = (instanceId, tags) => new Promise((resolve) => {
var params = { Resources: [instanceId], Tags: tags };
console.log('setting the following tags', params);
var aws = new AWS.EC2({ region: process.env.AWS_REGION }).createTags(params);
aws.on('success', r => {
resolve(r.data);
}).on('error', e => {
console.log('error in setTags', e.message);
}).send();
});

"x"在x.instanceId返回以下数组,虽然我知道getInstanceInfo部分是对Instanceid进行过滤,但我想从输出中返回要存储在变量中的平台值。


2022-12-16T05:54:10.721Z  d8de6c17-3152-463c-8b84-69b30bd740f5    INFO    {
InstanceIds: [
{
instanceId: 'i-02bfe033b04b2af74',
imageId: 'ami-0e863061578d3e9fb',
currentInstanceBootMode: 'bios',
instanceState: [Object],
privateDnsName: 'ip-10-100-11-217.us-west-2.compute.internal',
amiLaunchIndex: 0,
productCodes: {},
instanceType: 't2.micro',
launchTime: 1671170046000,
placement: [Object],
platform: 'windows',
monitoring: [Object],
subnetId: 'subnet-0b401fb2972ca8fda',
vpcId: 'vpc-02854f577f73bb8de',
privateIpAddress: '10.100.11.217',
stateReason: [Object],
architecture: 'x86_64',
rootDeviceType: 'ebs',
rootDeviceName: '/dev/sda1',
blockDeviceMapping: {},
virtualizationType: 'hvm',
hypervisor: 'xen',
tagSet: [Object],
clientToken: '098b4f57-1a79-46a8-ac63-d0cb6d7fa618',
groupSet: [Object],
sourceDestCheck: true,
networkInterfaceSet: [Object],
ebsOptimized: false,
enaSupport: true,
cpuOptions: [Object],
capacityReservationSpecification: [Object],
enclaveOptions: [Object],
metadataOptions: [Object],
maintenanceOptions: [Object],
privateDnsNameOptions: [Object]
}
]
}

我试着在箭头函数中添加一个返回,我肯定不会工作。

var instances = await Promise.all(event.detail.responseElements.instancesSet.items.map(x =>getInstanceInfo({instanceid: [x.]instanceId]}, x.platform)));

我试过采取实例,并试图只拉实例。未定义的平台。(我预料到)

我知道我可以使用:

var instances = await Promise.all(event.detail.responseElements.instancesSet.items.map(x => getInstanceInfo({ InstanceIds: [x.platform] })));

,它返回输出"window "但是这个函数失败了,因为过滤器正在寻找InstanceId。

我想在InstanceId上过滤,找到platform的值,并将其存储到一个变量中。

任何想法?

抱歉,如果这是不正确的格式或我没有提供足够的信息提前。虽然我经常使用Stack Overflow,但我还没有发布任何问题。

我可以通过创建正在调用的函数的变体来解决这个问题。只需修改resolve部分,从数组中获取一个特定的对象。

var InstanceIds = (params) => new Promise((resolve) => {
console.log(params)
var aws = new AWS.EC2({ region: process.env.AWS_REGION }).describeInstances(params);
aws.on('success', r => {
**resolve(r.data.Reservations[0].Instances[0].Platform)**;
}).on('error', e => {
console.log('error in describeInstances', e.message);
}).send();
});

我认为这应该工作,但由于某种原因,最初我有困难,实际上在我的第一次去实现它。也许数组元素是区分大小写的。谢谢你的帮助。

最新更新