我尝试使用以下代码创建cloudwatch事件规则。但是,它似乎不起作用。我检查了AWS CloudWatch Events,并且附带了附带的lambda函数。但是,该事件永远不会被触发。我该如何解决这个问题?
async function createCloudWatchEvent(zip){
if(zip){
try{
await putRule(zip);
await putTarget(zip);
} catch (e) {
console.log(`Can't create [${zip}] cloudwatch event`);
}
}
}
function putRule (ruleName) {
let cloudWatchParams = {
Name: ruleName, // required
ScheduleExpression: 'rate(1 minute)',
State: 'ENABLED'
};
return new Promise(resolve => {
cloudwatchevent.putRule(cloudWatchParams, async function(err, data) {
if(err){
console.log(err);
resolve(err);
}else{
console.log('Successfully created rule: ' + ruleName);
resolve();
}
});
});
}
function putTarget (ruleName) {
let cloudWatchParams = {
Rule: ruleName, // required
Targets: [ // required
{
Arn: 'xxxxxxxxxx',
Id: 'Determine_State',
Input: JSON.stringify({zip: ruleName})
}
]
};
return new Promise(resolve => {
// Attach "Determine_State" target to cloudwatch event
cloudwatchevent.putTargets(cloudWatchParams, function(err, data) {
if(err){
console.log(err);
resolve(err);
}else{
console.log('Successfully attached target [' + cloudWatchParams.Targets[0].Id + '] to rule: ' + ruleName);
resolve();
}
});
});
}
答案 0 :(得分:0)
我不确定您是否已经知道,您为lambda函数设置的cron时间表是否为UTC时间。例如,如果您指定5 pm,则为UTC时间5 pm。也许您正在执行日志之前对其进行检查。
lambda应该具有登录到cloudwatch的权限。否则,lambda函数不会将日志添加到cloudwatch。这是您可以参考的政策。
{
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Effect": "Allow",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
参考:
Can't get AWS Lambda function to log (text output) to CloudWatch
希望这会有所帮助。
答案 1 :(得分:0)
我认为您需要授予从CloudWatch事件(您的规则)中调用lambda函数的权限。看看this教程。
您必须通过CLI或从该语言的AWS API中进行操作。例如:
aws lambda add-permission \
--function-name LogScheduledEvent \
--statement-id my-scheduled-event \
--action 'lambda:InvokeFunction' \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-east-1:123456789012:rule/my-scheduled-rule