Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

adding AWS Lambda as target using AWS SDK for event bridge rule

I am using serverless framework and the AWS Node.js SDK for adding scheduled cron expression based rule to default event bus.

 eventBridge.putRule(params, function (err, data) {...

After that I add target to this rule.

const params = {
    Rule: data.ruleName,
    Targets: [ 
        {
            Arn: process.env.SCHEDULED_EVENT_LAMBDA_ARN, /* required */
            Id: process.env.SCHEDULED_EVENT_LAMBDA_ID, /* required */
            Input: JSON.stringify(someData)
        },
        
    ],
    
};

eventBridge.putTargets(params, function (err, data) {...

adding target is successful on the dynamically created scheduled cron rule on event bridge but when I navigate to lambda dashboard it does not seems like the triggering layer is updated and eventually the lambda function is not triggered.

The AWS SDK documentation for event bridge putTargets is mentioning:

For AWS Lambda and Amazon SNS resources, EventBridge relies on resource-based policies

So if the resource policy is the issue(not confirmed) is there any configuration regarding resource policy which I can set in serverless.yml file for a specific function that allows event-bridge service to add layer to deployed targated lambda function.

Upvotes: 3

Views: 1943

Answers (1)

samtoddler
samtoddler

Reputation: 9625

for dynamic generation you can use the AddPermission to add the necessary permissions.


function addPermission ({ lambdaArn, restApiId }) {
 const { region, namespace } = parseArn(lambdaArn)

 const params = {
  Action: 'lambda:InvokeFunction',
  FunctionName: lambdaArn,
  Principal: 'events.amazonaws.com',
  StatementId: `scheduleName`,
  SourceArn: `RuleARN`
 }

 return lambda.addPermission(params).promise()
}

If you are using serverless framework.

functions:
  myFunction:
    handler: index.handler
    events:
      - eventBridge:
          schedule: rate(10 minutes)
          input:
            key1: value1

The above definition simply create the rule and add your lambda as the target. It will take care of the necessary permissions as well whichever is needed.

Setting up event pattern matching

EventBridge Use Cases and Examples

Schedule

Upvotes: 4

Related Questions