Use Boto3 create EventBridge-Rule tigger Lambda Function
Tags: lambda, eventbridge, boto3, awscommunitybuilder
Published: 2022-08-18 03:07:00

# 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"

```python
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']
        )
```

# 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](https://us-east-1.console.aws.amazon.com/iam/home)

### 1.1.2 Create a role
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jg03zoytgi8nc86vx04g.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4lxnornanglmkld8ecee.png)


#### 1.1.2.1 use the json file

```json
{
  "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"
    }
  ]
} 
```  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1dbpg0ojxpp1qhdkwdmp.png)

#### 1.1.2.2 attach 2 policy to the role(lambda and event full access)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76cxs0s05c6ppg8qytsx.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rims5mn2xlwa5079z1m7.png)
#### 1.1.2.3 Remember the add_permission role ARN
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktzwdiccr774hswxdgzp.png)


## 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](https://us-east-1.console.aws.amazon.com/iam/home)

### 1.2.2 Create a role for lambda

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpwhqub3yyy48zsaa03c.png)

### 1.2.3 set a name **lambda_exec_role**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/os8ooe0rtqjhpj6ezv43.png)

### 1.2.4 check the role(not attach any policy)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e4hfa1apu5srym7o7otz.png)
 

## 1.3 Create a policy for lambda_exec_role
```json
{
    "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": "*"
        }
    ]
}
```

## 1.4 attach lambda_exec_role_policy to lambda_exec_role
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlz16lf3egvptfow7avc.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7gvhtry0hnrv404qcj9.png)
  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ija1h5hha42hrex7z425.png)
 
# 2.Create a lambda function

## 2.1 create a lambda function set runtime as python3.9

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ypv7oww695qlj129ja2.png)


## 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**

```python
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']
        )
``` 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjbon212ds9wf39ftlnk.png)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8q7fqkgnuw9fri4yeg0r.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1huy5uylshf4argol8hd.png)
  
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ud0pq6alo9j5fjfid8lj.png)

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