AWS Cloudwatch Event Rule - Invoke Lambda - with Parameter

那年仲夏 提交于 2021-02-19 08:34:19

问题


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"]}
                }]
            }
        },

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/61217571/aws-cloudwatch-event-rule-invoke-lambda-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!