DEV Community

Cover image for Use Boto3 create EventBridge-Rule tigger Lambda Function
Maverick Fung
Maverick Fung

Posted on

Use Boto3 create EventBridge-Rule tigger Lambda Function

Hi,Guys,This article I will teach you how to use python3 to create EventBridge Rule and tigger it to lambda function

If you don't have too much time,I will do this

somebody say:"Cut the crap and show me your code"

import os
import time
import boto3
from botocore.config import Config

lambda_client = boto3.client('lambda',config=Config(region_name=os.environ['AWS_REGION']))
event_client = boto3.client('events',config=Config(region_name=os.environ['AWS_REGION']))

def lambda_handler(event, context):
    rule_name = 'LeifengRule' # Define a var for rule_name
    cron_sec = 'cron(59 23 * * ? *)' # Define a var for cron
    lambda_fc_name = 'LeifengFC' # Define a var for lambda name
    lambda_fc_arn = 'arn:aws:lambda:us-east-1:xxxx:function:LeifengFC' # Here you need copy the lambda_fc_name function arn
    add_permission_role_arn = 'arn:aws:iam::xxxx:role/add_permission' # put create role ARN
    # use boto3 create a rule
    create_rule_resp = event_client.put_rule(
            Name=rule_name, # There put your rule name
            ScheduleExpression=cron_sec, # there put your cron
            State='ENABLED', # there set the rule state ENABLED or DISABLED
            EventBusName='default', # set eventbus ,I use default
            RoleArn=add_permission_role_arn
        )

    put_target_resp = event_client.put_targets(
            Rule=rule_name,
            Targets=[{
                'Id': lambda_fc_name,
                'Arn': lambda_fc_arn
            }]
        )

    # use if to determine the lambda_fc_arn weather '$' exists
    # if the '$' in lambda_fc_arn,just remove from $

    if '$' in lambda_fc_arn:
        lambda_fc_arn = lambda_fc_arn[:-8]
    add_lambda_permission = lambda_client.add_permission(
            FunctionName=lambda_fc_arn,
            StatementId=str(time.time())[-5:]+lambda_fc_name,
            Action='lambda:InvokeFunction',
            Principal='events.amazonaws.com',
            SourceArn=create_rule_resp['RuleArn']
        )
Enter fullscreen mode Exit fullscreen mode

1.Create IAM Role and Policy

1.1 Create add_permission role

1.1.1 Open AWS IAM console

Click here:https://us-east-1.console.aws.amazon.com/iam/home

1.1.2 Create a role

Image description

Image description

1.1.2.1 use the json file

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    },
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
} 
Enter fullscreen mode Exit fullscreen mode

Image description

1.1.2.2 attach 2 policy to the role(lambda and event full access)

Image description
Image description

1.1.2.3 Remember the add_permission role ARN

Image description

1.2 Create lambda execute role

1.2.1 Open AWS IAM console

Click here:https://us-east-1.console.aws.amazon.com/iam/home

1.2.2 Create a role for lambda

Image description

1.2.3 set a name lambda_exec_role

Image description

1.2.4 check the role(not attach any policy)

Image description

1.3 Create a policy for lambda_exec_role

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "events:DeleteRule",
                "events:PutTargets",
                "events:DescribeRule",
                "events:ListRuleNamesByTarget",
                "events:EnableRule",
                "events:PutRule",
                "events:ListRules",
                "events:RemoveTargets",
                "events:ListTargetsByRule",
                "events:DisableRule",
                "lambda:ListFunctions",
                "lambda:AddPermission",
                "iam:PassRole"
            ],
            "Resource": "*"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

1.4 attach lambda_exec_role_policy to lambda_exec_role

Image description
Image description

Image description

2.Create a lambda function

2.1 create a lambda function set runtime as python3.9

Image description

2.2 Copy the code to lambda

please replace rule_name cron_sec lambda_fc_name and lambda_fc_arn value

this code just show you

import os
import time
import boto3
from botocore.config import Config

lambda_client = boto3.client('lambda',config=Config(region_name=os.environ['AWS_REGION']))
event_client = boto3.client('events',config=Config(region_name=os.environ['AWS_REGION']))

def lambda_handler(event, context):
    rule_name = 'LeifengRule' # Define a var for rule_name
    cron_sec = 'cron(59 23 * * ? *)' # Define a var for cron
    lambda_fc_name = 'LeifengFC' # Define a var for lambda name
    lambda_fc_arn = 'arn:aws:lambda:us-east-1:xxxx:function:LeifengFC' # Here you need copy the lambda_fc_name function arn
    add_permission_role_arn = 'arn:aws:iam::xxxx:role/add_permission' # put create role ARN
    # use boto3 create a rule
    create_rule_resp = event_client.put_rule(
            Name=rule_name, # There put your rule name
            ScheduleExpression=cron_sec, # there put your cron
            State='ENABLED', # there set the rule state ENABLED or DISABLED
            EventBusName='default', # set eventbus ,I use default
            RoleArn=add_permission_role_arn
        )

    put_target_resp = event_client.put_targets(
            Rule=rule_name,
            Targets=[{
                'Id': lambda_fc_name,
                'Arn': lambda_fc_arn
            }]
        )

    # use if to determine the lambda_fc_arn weather '$' exists
    # if the '$' in lambda_fc_arn,just remove from $

    if '$' in lambda_fc_arn:
        lambda_fc_arn = lambda_fc_arn[:-8]
    add_lambda_permission = lambda_client.add_permission(
            FunctionName=lambda_fc_arn,
            StatementId=str(time.time())[-5:]+lambda_fc_name,
            Action='lambda:InvokeFunction',
            Principal='events.amazonaws.com',
            SourceArn=create_rule_resp['RuleArn']
        )
Enter fullscreen mode Exit fullscreen mode

Image description

Image description
Image description

Image description

If this article can help you, I will be very happy,Thank you ,have a nice day!

Top comments (0)