如何在无服务器框架中将CF资源定义为函数事件源

时间:2019-05-17 07:23:40

标签: serverless-framework aws-iot

我正在尝试使用无服务器框架创建一个AWS Lambda。 Lambda是通过AWS IoT主题规则触发的。万一规则执行失败,我想执行一个错误操作。整个配置应在 serverless.yml 中进行。

据我从documentation得知,没有任何选项可以为物联网事件描述errorAction

functions:
  foobar:
    events:
      - iot:
          errorAction: ?

尽管有可能在 serverless.yml 内用ErrorAction定义云形成资源:

resources:
  Resources:
     FoobarIotTopicRule1:
       Type: AWS::IoT::TopicRule
       Properties:
           ErrorAction:
             Republish:
               RoleArn: arn:aws:iam::1234567890:role/service-role/iot_execution_role
               Topic: FAILURE

但是然后我不知道如何链接资源以充当Lambda函数的触发器。

functions:
  foobar:
    handler: index.handler
    events:
      - iot:
          name: iot_magic_rule
          sql: "SELECT * FROM 'my/dedicated/topic'"
          enabled: true
          sqlVersion: '2016-03-23'

resources:
  Resources:
     FoobarIotTopicRule1:
       Type: AWS::IoT::TopicRule
       Properties:
         RuleName: iot_magic_rule
         TopicRulePayload:
           AwsIotSqlVersion: '2016-03-23'
           RuleDisabled: false
           Sql: "SELECT * FROM 'my/dedicated/topic'"
           ErrorAction:
             Republish:
               RoleArn: arn:aws:iam::1234567890:role/service-role/iot_execution_role
               Topic: FAILURE

使用上述配置,由于Cloud Formation尝试两次创建AWS IoT主题规则,因此尝试在AWS上部署失败。一次用于events中的定义,一次作为已定义资源FoobarIoTTopicRule1

EDIT1

在IoTTopicRule资源内定义Lambda操作,并按预期创建带有Lambda操作和错误事件的规则。不幸的是,该规则并未在Lambda中显示为触发条件。

1 个答案:

答案 0 :(得分:0)

要能够使用ErrorAction定义AWS IoT主题规则,该规则也将作为触发事件显示在AWS Lambda上,则配置应如下所示:

functions:
  foobar:
    handler: index.handler

resources:
  Resources:
     FoobarIotTopicRule1:
       Type: AWS::IoT::TopicRule
       Properties:
         RuleName: iot_magic_rule
         TopicRulePayload:
           AwsIotSqlVersion: '2016-03-23'
           RuleDisabled: false
           Sql: "SELECT * FROM 'my/dedicated/topic'"
           Actions:
             - Lambda:
                 FunctionArn: { "Fn::GetAtt": ['FoobarLambdaFunction', 'Arn']}
           ErrorAction:
             Republish:
               RoleArn: arn:aws:iam::1234567890:role/service-role/iot_execution_role
               Topic: FAILURE
     FoobarLambdaPermissionIotTopicRule1:
      Type: AWS::Lambda::Permission
      Properties: 
        FunctionName: { "Fn::GetAtt": [ "FoobarLambdaFunction", "Arn" ] }
        Action: lambda:InvokeFunction
        Principal: { "Fn::Join": ["", [ "iot.", { "Ref": "AWS::URLSuffix" } ]]}
        SourceArn: 
          Fn::Join: 
            - ""
            - - "arn:"
              - "Ref": "AWS::Partition"
              - ":iot:"
              - "Ref": "AWS::Region"
              - ":"
              - "Ref": "AWS::AccountId"
              - ":rule/"
              - "Ref": "FoobarIotTopicRule1"