首页 > 解决方案 > 为什么没有触发作为目标添加到事件桥规则的 Lambda 函数?

问题描述

我正在尝试将规则和 lambda 目标添加到 EventBridge 的规则中。规则和目标添加成功,但目标 Lambda 未触发。当我导航到 AWS 控制台上的目标 Lambda 函数时,我看不到相关的触发器。

我正在使用无服务器框架来部署堆栈。putRuleAndTargetlambda 是创建规则并添加notifyUser为目标的那个。这是文件的相关部分serverless.ts

functions: {
      putRuleAndTarget: {
            handler: 'src/functions/putRuleAndTarget.handler',
            name: 'putRuleAndTarget'
      },
      notifyUser: {
            handler: 'src/functions/notifyUser.handler',
            name: 'notifyUser'
      }
}

这是putRuleAndTarget(我正在使用 aws javascript sdk v3)的代码:

import { EventBridgeClient, PutRuleCommand, PutTargetsCommand, } from '@aws-sdk/client-eventbridge'
import type { PutRuleCommandInput, PutTargetsCommandInput } from '@aws-sdk/client-eventbridge'


const client = new EventBridgeClient({ region: 'eu-central-1' })

async function putRuleAndTarget( ) {
      try {
            const putRuleCommandInput: PutRuleCommandInput = {
                  Name: 'notifyUserRule',
                  Description: 'Schedule a lambda to send notification to the user',
                  ScheduleExpression: 'rate(1 minute)',
            }
            const putRuleCommand = new PutRuleCommand(putRuleCommandInput)
            const putRuleCommandOutput = await client.send(putRuleCommand)

            const putTargetsCommandInput: PutTargetsCommandInput = {
                  Rule: 'notifyUserRule',
                  Targets: [
                        {
                              Arn: 'arn:aws:lambda:eu-central-1:AccountID:function:notifyUser',
                              Id: 'notifyUser'
                        },
                  ]
            }
            const putTargetsCommand = new PutTargetsCommand(putTargetsCommandInput)
            const putTargetsCommandOutPut = await client.send(putTargetsCommand)
      

      } catch (error) {
            console.log('[ putRuleAndTarget error ]', error)
      }

}

export const handler = putRuleAndTarget

以下屏幕截图是putRuleAndTarget 在 AWS EventBridge 控制台上运行创建的规则后截取的: EventBridge 控制台 上的规则

显示目标的规则详细信息: EventBridge 控制台上的规则详细信息和目标

notifyUserLambda 控制台上的函数,请注意缺少触发器: Lambda 控制台上的 notifyUser 函数


此外,运行sls logs -f notifyUser不会带来任何日志语句,该函数永远不会被调用,尽管它应该每 1 分钟运行一次。

标签: node.jsamazon-web-servicesaws-lambdaserverless-frameworkaws-event-bridge

解决方案


看起来您可能缺少权限。该规则需要具有调用 lambda 的权限。

本教程显示了这些步骤。特别是,检查涵盖的部分

AWS::Lambda::Permission

评论中的请求示例:

 LambdaInvokePermissionsExample:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName:
        Fn::GetAtt:
          - NameOfYourLambdaResource
          - Arn
      Principal: events.amazonaws.com
      SourceArn:
        Fn::GetAtt:
          - EventRuleResourceName
          - Arn

推荐阅读