如何将json输入传递给使用事件在Serverless中部署的Cron计划Lambda?

时间:2016-11-02 17:48:38

标签: aws-lambda serverless-framework

我一直在尝试在Serverless中部署Lambda,以便在每小时调用它的Cron计划上运行。在调用它时,我希望Lambda中的事件由我自己的JSON输入填充,而不是来自Cron事件的信息,这是部署时的默认输入。

在AWS控制台内部,我可以手动进入Lambda的Cron触发器并更改"匹配事件"的输入。到"常数(JSON文本)"为了得到我想要的结果。由于Serverless在部署Lambda时创建了这个规则,我觉得应该有一些通过serverless.yml文件中的配置更改输入的方法。在搜索无服务器的文档时,我还没有找到任何东西,所以现在我想知道这是否可以通过无服务器处于当前状态,如果是,如何去做。

任何建议都将受到赞赏。

编辑:有一个应该添加了此功能的更新,但是我仍然无法使用无服务器1.3.0的JSON进行部署(并且还使用1.2.0进行了测试)。我使用的serverless.yml的一些例子如下:

functions:
  test:
    handler: test.test
    description: "test serverless Lambda"
    memorySize: 128
    timeout: 300
    events:
      - schedule:
        rate: rate(10 minutes)
        input:
          key: value
      - schedule:
        rate: rate(10 minutes)
        input: '{"key": "value"}'
      - schedule:
        rate: rate(10 minutes)
        input:
          key: 'value'

从1.3.0版本开始,无论是否我的serverless.yml看起来不错,是否有人能够对无服务器中此功能的状态发表评论?

编辑2:发布有效的serverless.yml

functions:
  test:
    handler: test.test
    description: "test serverless Lambda"
    memorySize: 128
    timeout: 300
    events:
      - schedule:
          rate: rate(10 minutes)
          enabled: true
          input:
            key: value
      - schedule:
          rate: rate(10 minutes)
          input: '{"key": "value"}'
          enabled: true
      - schedule:
          rate: rate(10 minutes)
          input:
            key: 'value'
          enabled: true

1 个答案:

答案 0 :(得分:14)

编辑你的编辑:我做了一些挖掘,似乎无服务器将自动禁用日程表,如果它不是一个字符串。这意味着如果您的整个活动都是- schedule: rate(10 minutes),则会启用该活动。但是,如果您有其他属性,则必须启用它,因为默认情况下它将被禁用。

所以你当前的.yml应该是这样的:

functions:   test:
    handler: test.test
    description: "test serverless Lambda"
    memorySize: 128
    timeout: 300
    events:
      - schedule:
        rate: rate(10 minutes)
        enabled: true
        input:
          key: value
      - schedule:
        rate: rate(10 minutes)
        input: '{"key": "value"}'
        enabled: true
      - schedule:
        rate: rate(10 minutes)
        input:
          key: 'value'
        enabled: true

您可以在serverless.yml文件中使用相同的inputinputPath,就像使用cloudwatch事件规则一样。与cloudwath规则的唯一区别在于,您实际上可以传递一个对象,无服务器将自动为您进行字符串化。

示例:

functions:
  crawl:
    handler: crawl
    events:
      - schedule: 
          rate: rate(1 hours)
          input: 
            key1: value1
            key2: value2

这将等于带有input:"{'key1':'value1','key2':'value2'}"的cloudformation事件规则,从而传递json而不是匹配事件。

刚才注意到问题是在11月2日提出的。当时不可能这样做但是在提出问题后很快就实施了。 https://github.com/serverless/serverless/pull/2567