简体   繁体   English

aws eventbridge 使用 aws-cdk python 将 ssm-document 设置为目标

[英]aws eventbridge set ssm-document as target with aws-cdk python

hope I did not overlook an already existing answer.. I would like to create an aws-cdk python stack containing an event that is starting an ssm-document when triggered.希望我没有忽略已经存在的答案。我想创建一个 aws-cdk python 堆栈,其中包含一个在触发时启动 ssm 文档的事件。 I got all the wanted stuff going in my aws test account, event is triggering on the desired actions and starts the ssm-document/run command with the correct targets (ec2 instances identified by some tags).我在我的 aws 测试帐户中获得了所有想要的东西,事件正在触发所需的操作,并使用正确的目标(由某些标签标识的 ec2 实例)启动 ssm-document/run 命令。 Now when it comes to Iac using aws-cdk python, I came to the boundary that it seems as if the aws_events_targets class ( https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_events_targets.html ) does not allow to set the diesired target for an event.. does anyone has a suggestion how to best work around this or the correct example for a blind man? Now when it comes to Iac using aws-cdk python, I came to the boundary that it seems as if the aws_events_targets class ( https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_events_targets. html )不允许为事件设置 diesired 目标.. 有没有人建议如何最好地解决这个问题或盲人的正确示例?

Use the AwsApi target and trigger the document with an API call to SSM.使用 AwsApi 目标并通过对 SSM 的 API 调用触发文档。

In short, it is not a valid approach because ssm-document is just a set of commands, not a system(application) or computing environment.简而言之,这不是一种有效的方法,因为 ssm-document 只是一组命令,而不是系统(应用程序)或计算环境。

I would decompose this process as follows:我将这个过程分解如下:

  • You have a ssm-document which should be used by ssm/run-command.您有一个 ssm-document,应该由 ssm/run-command 使用。 Document itself does not do anything.文档本身不做任何事情。
  • You have an event which should trigger the execution of the document.您有一个事件应该触发文档的执行。

According to this, I would stick to the design pattern for event-based business logic execution:据此,我将坚持基于事件的业务逻辑执行的设计模式:

Event source sends event to event Bus.事件源事件发送到事件总线。 Then EventBridge Rule catches it based on predefined pattern and activates Lambda which is going to execute a business logic (in our case ssm-document).然后 EventBridge Rule根据预定义的模式捕获它并激活Lambda ,它将执行一个业务逻辑(在我们的例子中是 ssm-document)。

So, let's get to code:所以,让我们开始代码:

Step 0步骤 0
I assume you have AWS CLI/CDK installed, project is set and you are already logged in.我假设您已安装 AWS CLI/CDK,已设置项目并且您已登录。

Step 1 - Declare and define Lambda and its Role第 1 步 - 声明并定义 Lambda 及其角色

import aws_cdk.aws_iam as _iam

lambda_role = _iam.Role(self, "lambda_role", 
role_name="lambda_role",
assumed_by=_iam.ServicePrincipal("lambda.amazonaws.com"),
managed_policies=[
    _iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaBasicExecutionRole"),
    _iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSServiceRoleX"),
    _iam.ManagedPolicy.from_aws_managed_policy_name("AWSRoleY")],
inline_policies={
"My_Custom_Name_For_Inline_Policy": _iam.PolicyDocument(statements=[
    _iam.PolicyStatement(
        effect=_iam.Effect.ALLOW, 
        actions=["ssm:*"],
        resources=["RESOURCE_ARN1", "RESOURCE_ARN1"])])})

As I do not have enough information to help you correctly define the role, I proposed all possible option how you can allow your Lambda function to run ssm-document.由于我没有足够的信息来帮助您正确定义角色,我提出了所有可能的选项,您可以如何允许您的 Lambda function 运行 ssm-document。 Here are some details:以下是一些细节:

  • service-role/AWSLambdaBasicExecutionRole is mandatory service-role/AWSLambdaBasicExecutionRole是强制性的
  • service-role/AWSServiceRoleX is meant for any service-based AWS managed roles. service-role/AWSServiceRoleX适用于任何基于服务的 AWS 托管角色。 Replace it with the correct one(s) in case of need.需要时用正确的替换它。
  • AWSRoleY is meant for general AWS-managed roles. AWSRoleY适用于一般 AWS 托管角色。 Replace it with the correct one(s) in case of need.需要时用正确的替换它。
  • I also added inline_policies in case you need to granularly define what exactly you want to allow your Lambda role to do.我还添加了inline_policies以防您需要详细定义您想要让您的 Lambda 角色执行的操作。
import aws_cdk.aws_lambda as _lambda

lambda_ = _lambda.Function(self, "my_lambda", 
    function_name="my_lambda",
    architecture=_lambda.Architecture.ARM_64,
    runtime=_lambda.Runtime.PYTHON_3_9, 
    role=lambda_role, 
    log_retention=_logs.RetentionDays.THREE_MONTHS,
    timeout=cdk.Duration.minutes(3), 
    retry_attempts=0, 
    code=_lambda.Code.from_asset("./assets/lambda_code/"), 
    handler="lambda_main.lambda_handler")

Again, In this case I am lacking some information but I assume this might be a strucutre of your Lambda function:同样,在这种情况下,我缺少一些信息,但我认为这可能是您的 Lambda function 的结构:

  • As we are using Python3.9 runtime and we do not have any complicated 3rd-party dependencies - we can use ARM architecture .由于我们使用的是 Python3.9 运行时并且我们没有任何复杂的 3rd-party 依赖项 - 我们可以使用ARM 架构
  • lambda_role refers to previously defined role. lambda_role指的是先前定义的角色。
  • I also added log_retention for 3 months, removed retry_attempts and set 3 min timeout .我还添加了log_retention 3 个月,删除retry_attempts并设置了 3 min timeout These are optional and should be used/adjusted based on your preference.这些是可选的,应根据您的喜好使用/调整。
  • code refers to block which I will provide in the next block. code是指我将在下一个块中提供的块。 If you want to following the proposed structure then in the root of the project you will need to create dir called lambda_code , inside it you will script named lambda_main.py如果您想遵循建议的结构,则需要在项目的根目录中创建名为lambda_code的目录,在其中您将编写名为lambda_main.py脚本
  • The function which will be called by Lambda has default name - lambda_handler .将由 Lambda 调用的 function 具有默认名称 - lambda_handler

Lambda code which hold business logic (run ssm-document):包含业务逻辑的 Lambda 代码(运行 ssm-document):

import boto3

_ssm = boto3.client('ssm')


def lambda_handler(event, context):
    print(event)
    response = ssm_client.send_command(
                InstanceIds=['i-01234567890'],
                DocumentName="AWS-RunShellScript",
                Parameters={'commands': ['whoami']})

    command_id = response['Command']['CommandId']
    
    return ssm_client.get_command_invocation(CommandId=command_id, InstanceId='i-01234567890')

In this example I decided to use AWS-RunShellScript document, which you should substitute with the one you need.在此示例中,我决定使用AWS-RunShellScript文档,您应该将其替换为您需要的文档。 Be default, parameters also should be changed.默认情况下,参数也应该更改。

Step 2 - Declare and define EventBridge Rule第 2 步 - 声明和定义 EventBridge 规则

import aws_cdk.aws_events as _events
import aws_cdk.aws_events_targets as _targets

# Based on CRON
_events.Rule(self, "trigger_rule_sync", 
    rule_name="my_rule_name", 
    enabled=True, 
    schedule=_events.Schedule.cron(minute="0", hour="8"),
    targets=[_targets.LambdaFunction(handler=lambda_tableau_deployment)])

# Based on EVENT PATTERN
_events.Rule(self, "trigger_rule_sync", 
    rule_name="my_rule_name", 
    enabled=True, 
    event_pattern=_events.EventPattern(
        resources=["ARN_OF_MY_CODECOMMIT_REPO"], 
        detail={"event": ["referenceUpdated"], "referenceName": ["prod", "dev"]}),
    targets=[_targets.LambdaFunction(handler=lambda_tableau_deployment)])

In this snippet I provided both triggering by schedule and triggering by event.在这个片段中,我提供了按计划触发和按事件触发。 As an event I assumed that I want to trigger my lambda when I commit something to by prod or dev branch in AWS CodeCommit.作为一个事件,我假设当我通过 AWS CodeCommit 中的 prod 或 dev 分支提交某些内容时,我想触发我的 lambda。 (weird, but why not?). (奇怪,但为什么不呢?)。 Details of code can be found in boto3 documentation .代码的详细信息可以在boto3 文档中找到。

Step 3 - Sync, deploy and check第 3 步 - 同步、部署和检查

When everything is ready, give it a try and verify that final result matches the expected one.一切准备就绪后,试一试并验证最终结果是否符合预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用aws-cdk测试lambda(Python)? - Testing lambdas (Python) with aws-cdk? AWS-CDK 无法在 Python 中导入核心 - AWS-CDK cannot import core in Python 如何使用 CDK 部署 aws EventBridge - Python 示例 - How to deploy aws EventBridge with CDK - Python example 如何在 python 中为 aws-cdk 创建自定义构造库 - How to create custom construct library for aws-cdk in python 如何使用 Python AWS-CDK 将现有资源添加到堆栈? - How to add an existing resource to stack using Python AWS-CDK? 使用 aws-cdk(python) 更新 redis 集群的问题 - issue with updating redis cluster using aws-cdk(python) 有没有办法使用 AWS-CDK 将新的 lambda function 连接到现有的 AWS ApiGateway? (Python) - Is there a way to connect a new lambda function an existing AWS ApiGateway using AWS-CDK? (Python) AWS CDK ssm.CfnAssociation 定义参数 - AWS CDK ssm.CfnAssociation define parameters 如何使用 aws-cdk for python 在一个 cloudwatch 图中获取多个 lambda - How to get multiple lambdas in one cloudwatch graph using aws-cdk for python 如何使用 python 中的 aws-cdk 设置 Amazon S3 通知以在您的存储桶中发生某些事件时接收通知? - How do I set up Amazon S3 notification to receive notifications when certain events happen in your bucket using aws-cdk in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM