I try to dynammicly trigger my lambda by create rule , add lambda as target to that rule and add permission to the rule to invoke the lambda as follow:
const client = new CloudWatchEventsClient({
region: region,
credentials: { accessKeyId, secretAccessKey }
});
//for simplicity i make constant variables here:
const ruleName = "sendEmail-test-1"
const cron= "(10 10 ? * * *)"
const event = {foo:"boo"}
const putRule = async () => {
const command = new PutRuleCommand({
Name: ruleName,
ScheduleExpression: cron,
State: 'ENABLED',
Description: Description
});
return await client.send(command);
putRule
return metadaa with status code of 200 . also in the UI i can see the new rule.
Then I add target to this rule as follow:
const putTarget = async (ruleName: string, event: RuleObjectType['event']) => {
const command = new PutTargetsCommand({
Rule: ruleName,
Targets: [
{
Id: ruleName,
Arn: lambdaARN,
Input: JSON.stringify(event)
}
]
});
return await client.send(command);
};
Same here the status code in the response is 200 , and I can see in the UI that the rule has a new target which is my lambda.
But if I go the the lambda I dont see in triggers the new rule yet , so I add a permission to this rule inside the lambda as follow:
const addLambdaPermission = async (ruleName: string) => {
const command = new AddPermissionCommand({
Action: 'lambda:InvokeFunction',
FunctionName: lambdaARN,
Principal: 'events.amazonaws.com',
SourceArn: `arn:aws:events:${region}:${IAM_ID}:rule/${ruleName}`,
StatementId: `myProject-MyLambda-${ruleName}-permission` // Unique statement ID
});
return await client.send(command as any);
};
Again the response is with status code of 200 but still i dont see any changes
inside the lambda permission I dont see this new permission
inside lambda triggers i dont see the rule I just added.
What am I missing?
2
Answers
After reviewing the documentation AddPermissionCommand I realized that each AWS service has its own dedicated client. To successfully add permissions, I needed to create separate instances for the CloudWatch Events and Lambda clients.
To correct it I was needed to import the lambda client :
By separating the client instances, I was able to successfully add the permission to my Lambda function, allowing it to be invoked by EventBridge.
I concerned that you have IAM role for it? Can you show the throw exception message? put it in try catch and figure it out. I don’t know exactly, but I see
EventBusName
andRoleArn
is so important.