gpt4 book ai didi

node.js - 如何将位于 S3 中的 node.js 脚本与 Cloudwatch 合成金丝雀一起使用?

转载 作者:行者123 更新时间:2023-12-03 07:41:59 24 4
gpt4 key购买 nike

我有一个使用嵌入式 node.js 脚本的 Cloudwatch Canary,但希望 Node 脚本位于 S3 中,然后让 lambda 引用该脚本。我们希望导出一些 Cloudformation 参数(主机名、路径和端口)并将它们作为输入传递到要使用的 Node.js 脚本中。

我尝试遵循 AWS documentation在金丝雀上为此,但我仍然收到错误:

信息:error.toString() 和 error.stack.toString():错误:找不到模块“/opt/nodejs/node_modules/exports”堆栈:错误:找不到模块“/opt/nodejs/node_modules/exports” '

我的 Cloudformation 模板在这里:

Parameters:
CanaryName:
Type: String
Default: my-canary
MaxLength: 21
HostName:
Type: String
Default: api.net
MaxLength: 128
Path:
Type: String
Default: /v1/status
MaxLength: 256
Port:
Type: Number
Default: 443

Resources:
CloudWatchSyntheticsRole:
Type: AWS::IAM::Role
Properties:
RoleName:
Fn::Sub: CloudWatchSyntheticsRole-${CanaryName}-${AWS::Region}
Description: CloudWatch Synthetics lambda execution role for running canaries
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Condition: {}

RolePermissions:
Type: AWS::IAM::Policy
Properties:
Roles:
- Ref: CloudWatchSyntheticsRole
PolicyName:
Fn::Sub: CloudWatchSyntheticsPolicy-${CanaryName}-${AWS::Region}
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- s3:PutObject
- s3:GetBucketLocation
- s3:GetObject
- s3:GetObjectVersion
Resource:
- Fn::Sub: arn:aws:s3:::${ResultsBucket}/*
- Effect: Allow
Action:
- logs:CreateLogStream
- logs:PutLogEvents
- logs:CreateLogGroup
Resource:
- Fn::Sub: arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/cwsyn-test-*
- Effect: Allow
Action:
- s3:ListAllMyBuckets
Resource: '*'
- Effect: Allow
Resource: '*'
Action: cloudwatch:PutMetricData
Condition:
StringEquals:
cloudwatch:namespace: CloudWatchSynthetics
- Effect: Allow
Action:
- ssm:getParameter
Resource: "*"

ResultsBucket:
Type: AWS::S3::Bucket
Properties:
BucketName:
Fn::Sub: cw-syn-results-${AWS::AccountId}-${AWS::Region}
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256

Canary:
Type: AWS::Synthetics::Canary
Properties:
Name:
Fn::Sub: ${CanaryName}
Code:
Handler: exports.handler
S3Bucket: canary-source-code-ACCOUNT-us-east-1
S3Key: exports.zip
ExecutionRoleArn:
Fn::GetAtt:
- CloudWatchSyntheticsRole
- Arn
RuntimeVersion: syn-nodejs-2.0
RunConfig:
TimeoutInSeconds: 60
ArtifactS3Location:
Fn::Join:
- ''
- - s3://
- Ref: ResultsBucket
StartCanaryAfterCreation: True
Schedule:
Expression: rate(5 minutes) # every minute
DurationInSeconds: 0 # run indefinitely
SuccessRetentionPeriod: 5
FailureRetentionPeriod: 30

Outputs:
CanaryRoleArn:
Value:
Fn::GetAtt:
- CloudWatchSyntheticsRole
- Arn
ResultsBucketArn:
Value:
Fn::GetAtt:
- ResultsBucket
- Arn
ResultsBucketName:
Value:
Ref: ResultsBucket

我的 Node 脚本代码在这里:

'use strict';
const AWS = require('aws-sdk')
const parameterStore = new AWS.SSM()

// Read SSM

AWS.config.update({
region: 'us-east-1'
})

const getParam = param => {
return new Promise((res, rej) => {
parameterStore.getParameter({
Name: param,
WithDecryption: true

}, (err, data) => {
if (err) {
return rej(err)
}
return res(data)
})
})
}

module.exports.get = async (event, context) => {
const param = await getParam(param)
console.log(param);
return {
statusCode: 200,
body: JSON.stringify(param)
};
};

var synthetics = require('Synthetics');
const log = require('SyntheticsLogger');
const https = require('https');

const apiCanaryBlueprint = async function () {
const postData = "";

var tempsecret = await getParam('token')
const secret = tempsecret.Parameter.Value

var temphostname = await getParam('hostname')
const hostname = temphostname.Parameter.Value

var temppath = await getParam('path')
const path = temppath.Parameter.Value

var tempport = await getParam('port')
const port = tempport.Parameter.Value

const verifyRequest = async function (requestOption) {
return new Promise((resolve, reject) => {
log.info("Making request with options: " + JSON.stringify(requestOption));
let req
req = https.request(requestOption);

req.on('response', (res) => {
log.info(`Status Code: ${res.statusCode}`)
log.info(`Response Headers: ${JSON.stringify(res.headers)}`)

// If the response status code is not a 2xx success code
if (res.statusCode < 200 || res.statusCode > 299) {
reject("Failed: " + requestOption.path);
}
res.on('data', (d) => {
log.info("Response: " + d);
});
res.on('end', () => {
resolve();
})
});

req.on('error', (error) => {
reject(error);
});

if (postData) {
req.write(postData);
}
req.end();
});
}
const headers = { "Authorization" : secret}
headers['User-Agent'] = [synthetics.getCanaryUserAgentString(), headers['User-Agent']].join(' ');
const requestOptions = { "hostname" : hostname, "method" : "GET", "path" : path, "port" : port }
requestOptions['headers'] = headers;
await verifyRequest(requestOptions);
};

exports.handler = async () => {
return await apiCanaryBlueprint();
};

我读到该文件必须采用 .zip 格式,并且必须与处理程序名称一致,在本例中为 Exports.handler,如我上面所述。我对 CloudWatch 的这一部分很陌生,因此我可以使用一些指导来了解可能出现的问题。

最佳答案

我怀疑您没有将文件放入此结构中导出.zip└nodejs/node_modules/apiCanaryBlueprint.js

关于node.js - 如何将位于 S3 中的 node.js 脚本与 Cloudwatch 合成金丝雀一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64598711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com