arykalin
arykalin

Reputation: 403

How to add cloudwatch event trigger to AWS lambda using cloudformation?

I need to make a cloudformation template with lambda and cloudwatch event which will trigger it periodically. Here is my template:

  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

This code is creating a lambda and event rule which is pointing to lambda. enter image description here But it don't create trigger in lambda itself. If I add trigger manually it's working fine. What I'm doing wrong?

Upvotes: 3

Views: 3052

Answers (1)

jogold
jogold

Reputation: 7407

When working with a AWS::Serverless::Function resource, you can include the events/triggers in the resource properties:

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)

Permissions for CloudWatch Events to invoke your function are handled automatically.

Upvotes: 3

Related Questions