How to create eventbridge rule using boto3 with lambda function as target?

Viewed 4436

I wanted to create an AWS eventbridge rule with lambda function as the target. The lambda function named 'StartInstance' has been already created via console.

I have created a python script which is using boto3 library to create this eventbridge rule. I am passing a cron expression to this rule which would invoke the lambda function at a particular date and time.

Here is the code of python script which runs successfully:

import boto3

eventclient = boto3.client('events')

response = eventclient.put_rule(
    Name='ec2scheduler',
    ScheduleExpression='cron(40 16 21 4 ? 2021)',
    State='ENABLED',
    Description='schedule ec2 start/stop'
)

response = eventclient.put_targets(
    Rule='ec2scheduler',
    Targets=[
        {
            'Id': 'StartInstance',
            'Arn': 'arn:aws:lambda:us-east-1:965477548122:function:StartInstance'
        }
    ]
)

As you can see, cron expression passed to the rule is: cron(40 16 21 4 ? 2021) Which should have invoked the 'StartInstance' lambda function on Date 21-April-2021 at 16:40 hrs GMT. However, the lambda function didn't get invoked at that time. I see no logs generated for lambda function in cloudwatch logs as well. The eventbridge rule created above looks fine to me when I see it via AWS Eventbridge console with the required target and cron expression visible in console. But the rule doesn't invoke the lambda function when time comes.

Why is this happening?

2 Answers

TLDR: Permissions/Trust needs to be established on lambda and eventbridge

Explanation

Couple of things missing here:

First:

When you add a rule and a target from the console, AWS does the job of creating a lambda event source mapping. In this case, the EventBridge rule should be configured as the event source for the lambda function.

The create_event_source_mapping lambda API will let you add this mapping explicitly. This has to be done in the code after you create the target and the rule.

Second:

In the parameters for the put_rule EventBridge API, I don't see the RoleArn mentioned. The ARN for the role which the rule will use needs to have the permission to invoke the target lambda function.

Attach the policy AmazonEventBridgeFullAccess to the role.

Related