如何使用cloudformation将cloudwatch事件触发器添加到AWS lambda?

时间:2019-08-01 13:34:38

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

我需要使用lambda和cloudwatch事件制作一个cloudformation模板,这将定期触发它。这是我的模板:

  CertPolicyLambda:
    Type: AWS::Serverless::Function
    Properties:
      Handler: cert-policy
      Runtime: go1.x
      CodeUri: s3://venafi-policy-sam/73b1ee5fab9f9f089838227389c27273
      Description: Venfi policy with a RESTful API endpoint using Amazon API Gateway.
      MemorySize: 512
      Timeout: 10
      Role:
        Fn::Sub: arn:aws:iam::${AWS::AccountId}:role/lambda-venafi-role
          S3_BUCKET: cert-policy-lambda
  ScheduledRule:
    Type: AWS::Events::Rule
    Properties:
      Description: ScheduledRule
      ScheduleExpression: rate(1 minute)
      State: ENABLED
      Targets:
      - Arn:
          Fn::Sub: ${CertPolicyLambda.Arn}
        Id:
          Ref: CertPolicyLambda
  PermissionForEventsToInvokeLambda:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName:
        Ref: CertPolicyLambda
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn:
        Fn::GetAtt:
        - CertPolicyLambda
        - Arn

此代码创建一个lambda和事件规则,该规则指向lambda。 enter image description here 但是它不会在lambda本身中创建触发器。如果我手动添加触发器,则可以正常工作。我在做什么错了?

1 个答案:

答案 0 :(得分:2)

使用AWS::Serverless::Function资源时,可以在资源属性中包括事件/触发器:

CertPolicyLambda:
  Type: 'AWS::Serverless::Function'
  Properties:
    Handler: cert-policy
    Runtime: go1.x
    CodeUri: s3://venafi-policy-sam/73b1ee5fab9f9f089838227389c27273
    ...
    Events:
      OneMinute: # Trigger every minute
        Type: Schedule
        Properties:
          Schedule: rate(1 minute)

CloudWatch Events调用您的函数的权限会自动处理。