Boto3를 사용하여 EventBridge-Rule tigger Lambda 함수 생성

안녕, 얘들아, 이 기사에서는 python3을 사용하여 EventBridge 규칙을 생성하고 이를 람다 함수로 트리거하는 방법을 알려줄 것이다.



시간이 많지 않다면 내가 할게.



누군가가 말합니다: "쓰레기 그만하고 당신의 코드를 보여주세요"




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. IAM 역할 및 정책 생성



1.1 add_permission 역할 생성



1.1.1 AWS IAM 콘솔 열기



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

1.1.2 역할 만들기







1.1.2.1 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"
    }
  ]
} 




1.1.2.2 역할에 2 정책 첨부(람다 및 이벤트 전체 액세스)





1.1.2.3 add_permission 역할 ARN 기억




1.2 람다 실행 역할 생성


1.2.1 AWS IAM 콘솔 열기



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

1.2.2 람다에 대한 역할 생성




1.2.3 lambda_exec_role 이름 설정




1.2.4 역할 확인(정책을 첨부하지 않음)




1.3 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": "*"
        }
    ]
}

1.4 lambda_exec_role_policy를 lambda_exec_role에 연결







2.람다 함수 만들기


2.1 Python3.9로 람다 함수 세트 런타임 생성




2.2 코드를 람다에 복사



rule_name cron_sec lambda_fc_name 및 lambda_fc_arn 값을 바꾸십시오.

이 코드는 당신을 보여줍니다

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









이 기사가 도움이 된다면 매우 기쁠 것입니다. 감사합니다. 좋은 하루 되세요!

좋은 웹페이지 즐겨찾기