首页 文章

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

提问于
浏览
16

我一直在尝试在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 回答

  • 11

    编辑你的编辑:我做了一些挖掘,似乎无服务器将自动禁用日程安排,如果它不是一个字符串 . 意味着如果您的整个事件都是 - 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事件规则一样 . 与 Cloud 计划规则的唯一区别在于,您实际上可以传递一个对象,无服务器将自动为您进行字符串化 .

    例:

    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

相关问题