阅读背景:

在AWS Lambda代码中动态添加CloudwatchEvent

来源:互联网 

I have a Lambda function triggered by S3 file Put event.Now once the lambda is triggered i want to attach cloudwatch event(cron) to the same lambda in the code.Is it possible?

我有一个由S3文件触发事件触发的Lambda函数。现在,一旦lambda被触发,我想将cloudwatch事件(cron)附加到代码中的同一个lambda。这可能吗?

2 个解决方案

#1


1  

You need to do 2 things to accomplish this

你需要做两件事才能做到这一点

  1. Add a target(lambda) in the cloudwatch rule (cron)
  2. 在cloudwatch规则(cron)中添加目标(lambda)
  3. Add permission in lambda to allow the rule to invoke the lambda
  4. 在lambda中添加权限以允许规则调用lambda

I don't have an exact code sample to give you, but the below snippets will have to be included in your function to achieve this -

我没有准确的代码示例给您,但下面的代码片段必须包含在您的函数中才能实现此目的 -

import boto3

event_client = boto3.client('events')
event_response = event_client.put_targets(
    Rule=RULENAME,
    Targets=[{
            'Id': 'A_UNIQUE_STRING',
            'Arn': 'ARN_LAMBDA'
        }]
)

lambda_client = boto3.client('lambda')
lambda_response = lambda_client.add_permission(
    FunctionName="LAMBDA_NAME",
    StatementId="A_UNIQUE_STRING",
    Action="lambda:InvokeFunction",
    Principal="events.amazonaws.com",
    SourceArn="ARN_RULE"
)

ARN_LAMBDA should be something like - arn:aws:lambda:<aws-region>:<aws-account-number>:function:<lambda-name>

ARN_LAMBDA应该类似于 - arn:aws:lambda: :function:

ARN_RULE should be something like - arn:aws:events:<aws-region>:<aws-account-number>:rule/<rule-name>

ARN_RULE应该类似于 - arn:aws:events: :rule /

A_UNIQUE_STRING - you can generate something in your code which is meaningful and unique or just a random string.

A_UNIQUE_STRING - 您可以在代码中生成有意义且唯一的内容或只是随机字符串。

You can refer the guides in the boto3 documentation of lambda and cloudwatch events for more details - https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.add_permission https://boto3.readthedocs.io/en/latest/reference/services/events.html#CloudWatchEvents.Client.put_targets

您可以参考lambda和cloudwatch事件的boto3文档中的指南以获取更多详细信息 - https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.add_permission http:// boto3 .readthedocs.io / EN /最新/参考/服务/ events.html#CloudWatchEvents.Client.put_targets

#2


0  

This should be possible for non-streaming triggers but you need to handle the two different event types in code.

这应该适用于非流式触发器,但您需要在代码中处理两种不同的事件类型。

On the other hand it would be better to use two seperate Lambdas since you will be only paying for the usage.

另一方面,最好使用两个单独的Lambdas,因为您只需支付使用费。


分享到: