如何创建一个由对流层的云观察事件定期调用的Lambda?

时间:2017-06-27 16:49:26

标签: aws-lambda amazon-cloudwatch amazon-cloudformation troposphere

我创建了一个Lambda函数,我想每隔5分钟调用一次,或者每天调用一次,或者其他什么。我如何用对流层进行设置?

我无法在任何地方找到示例。

1 个答案:

答案 0 :(得分:8)

对于下一个人,这是我最终提出的工作代码(在这种情况下,我正在尝试运行“报告”):

from troposphere import (
    Join, Ref, GetAtt, awslambda, iam, events, Template
)

template = Template()

report_lambda = template.add_resource(awslambda.Function(
    "MyLambda",
    Code=awslambda.Code(
        S3Bucket="my-bucket"
        S3Key="lambdas/my-lambda.jar"
    ),
    Description="Lambda task that runs every 5 minutes.",
    FunctionName="MyFunction",
    Handler="com.mycompany.MyLambda::handleRequest",
    Runtime="java8",
    Timeout=120,
    Role=GetAtt("MyLambdaRole", "Arn"),
    MemorySize=512
))

report_rule = template.add_resource(events.Rule(
    "MyRule",
    ScheduleExpression="rate(5 minutes)",
    Description="My Lambda CloudWatch Event",
    State="ENABLED",
    Targets=[
        events.Target(
            "MyLambdaTarget",
            Arn=GetAtt(report_lambda.title, "Arn"),
            Id="MyLambdaId"
        )
    ]
))

template.add_resource(awslambda.Permission(
    'MyInvokePermission',
    FunctionName=GetAtt(report_lambda.title, 'Arn'),
    Action='lambda:InvokeFunction',
    Principal='events.amazonaws.com',
    SourceArn=GetAtt(report_rule.title, 'Arn'),
))

print(template.to_json())