1
votes

I am using AWS Clouwatch Event Rule to invoke a python lambda function based on Cron Schedule which is working fine.Now can I pass parameter into this lambda function from cloudwatch even rule using AWS Cloudformation? Could you please guide? Please see below my cfn template :

Step1 : parameter.Schedule=cron(0 21 ? * * *)

Step 2: "Schedule": {
            "Description": "Schedule for the Lambda function (cron or rate)",
            "Type": "String"
          },


Step 3:  "funcInvokeRule": {
            "Type": "AWS::Events::Rule",
            "Properties": {
                "ScheduleExpression": {"Ref": "Schedule"},
                "Targets": [{
                    "Id": "funcScheduler",
                    "Arn": {"Fn::GetAtt": ["Function","Arn"]}
                }]
            }
        },
2

2 Answers

1
votes

Following the AWS docs, your cloudformation resource could be as simple as:

Resources:  
  EventRule:
    Type: AWS::Events::Rule
    Properties:
      Name: {EVENTNAME}
      Description: "ScheduledRule"
      ScheduleExpression: cron(0 21 ? * * *)
      State: "ENABLED"
      RoleArn: {ROLE}

Replacing Name and RoleArn with your own values.

Note: Name is not a required parameter but does help identify your resources. However, as per the documentation, if you replace the resource in your cloudformation template you specify a new name.

If you were then also going to use cloudformation for your lambda using severless, personally I would then attached the rule to the lambda via permissions, that way you can attach up to 5 triggers on the rule without modifying the rule targets every time. e.g.

  Lambda:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName:{LAMBDANAME}
      Description: {Description}
      Role: {Role}
      Handler: {FileName}.lambda_handler
      Runtime: {x}
      CodeUri: {ObjectPath}
      MemorySize: {x}
      Timeout: {x}
  Lambdatrigger:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref Lambda
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !Ref EventRule
0
votes

The Target property type of AWS::Events::Rule has Input parameter:

Valid JSON text passed to the target. If you use this property, nothing from the event text itself is passed to the target.

There is also InputTransformer which you can use to transform existing input, by for example, adding extra values to it.

Settings to enable you to provide custom input to a target based on certain event data. You can extract one or more key-value pairs from the event and then use that data to send customized input to the target.