[英]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:我将这个过程分解如下:
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.需要时用正确的替换它。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 的结构:
lambda_role
refers to previously defined role. lambda_role
指的是先前定义的角色。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
脚本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.