每天安排一次lambda函数

时间:2019-05-08 13:25:19

标签: amazon-cloudformation

我有一个cloudformation模板,可以正常工作。它会安装python lambda函数。

https://github.com/shantanuo/easyboto/blob/master/install_lambda.txt

但是如何每天运行一次该功能?我知道yaml代码看起来像这样...

  NotifierLambdaScheduledRule:
    Type: AWS::Events::Rule
    Properties:
      Name: 'notifier-scheduled-rule'
      Description: 'Triggers notifier lambda once per day'
      ScheduleExpression: cron(0 7 ? * * *)
      State: ENABLED

换句话说,如何将cron设置集成到我的cloudformation模板中?

2 个答案:

答案 0 :(得分:1)

我使用的示例:

  # Cronjobs
  ## Create your Lambda
  CronjobsFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: FUNCTION_NAME
      Handler: index.handler
      Role: !GetAtt LambdaExecutionRole.Arn
      Code:
        S3Bucket: !Sub ${S3BucketName}
        S3Key: !Sub ${LambdasFileName}
      Runtime: nodejs8.10
      MemorySize: 512
      Timeout: 300

  ## Create schedule
  CronjobsScheduledRule:
    Type: AWS::Events::Rule
    Properties:
      Description: Scheduled Rule
      ScheduleExpression: cron(0 7 ? * * *)
      # ScheduleExpression: rate(1 day)
      State: ENABLED
      Targets:
        - Arn: !GetAtt CronjobsFunction.Arn
          Id: TargetFunctionV1

  ## Grant permission to Events trigger Lambda
  PermissionForEventsToInvokeCronjobsFunction:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref CronjobsFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt CronjobsScheduledRule.Arn

  ## Create Logs to check if events are working
  CronjobsFunctionLogsGroup:
    Type: AWS::Logs::LogGroup
    DependsOn: CronjobsFunction
    DeletionPolicy: Delete
    Properties:
      LogGroupName: !Join ['/', ['/aws/lambda', !Ref CronjobsFunction]]
      RetentionInDays: 14

您可以查看有关费率和Cron表达式here

答案 1 :(得分:0)

其他人可以为您提供不带Serverless的Lambda示例。但是,如果您将无服务器转换与AWS Cloudformation结合使用(基本上是SAM-无服务器应用程序模型),则可以轻松安排lambda。

例如:

  ServerlessTestLambda:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src
      Handler: test-env-var.handler
      Role: !GetAtt BasicLambdaRole.Arn
      Environment:
        Variables:
          Var1: "{{resolve:ssm:/test/ssmparam:3}}"
          Var2: "Whatever You want"
      Events:
        LambdaSchedule:
          Type: Schedule
          Properties:
            Schedule: rate(3 minutes)

此lambda会每3分钟触发一次。

更多信息:https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#schedule