0

TL; DR:我应该如何编辑下面的模板,以便它可以被用户池触发器触发?

我尝试为 Lambda 函数创建一个 CloudFormation 模板,定义该函数可以调用和从中调用的服务。它应该使用 Cognito 用户池触发器运行。

为此,我在模板类型中定义了一个资源,AWS::Serverless::Function如下所示。注意Policies部分:

Resources:
  MyFunctionResource:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: MyFunctionName
      CodeUri: ./
      Handler: "lambda_function.lambda_handler"
      MemorySize: 128
      Runtime: python3.7
      Timeout: 3
      Policies:
        - Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action:
                - "cognito-idp:*"
                - "logs:*"
                ...
              Resource: "*"
        - Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action: "lambda:InvokeFunction"
              Principal:
                Service: cognito-idp.amazonaws.com
              Resource: !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:MyFunctionName"

我插入的用于限制资源的第二个策略可以调用我的函数在堆栈创建期间失败:

政策文件不应指定委托人。(服务:AmazonIdentityManagement;状态代码:400;错误代码:MalformedPolicyDocument;请求 ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

当我使用 principal删除该策略时,通过用户池触发器访问该功能被拒绝。

4

1 回答 1

1

我发现权限应该创建为一个单独的资源,其类型AWS::Lambda::Permission可以采用函数名称或将附加到的 arn。

因此,以下逻辑成功地创建了具有权限的函数(也称为函数策略):

Resources:
  MyFunctionResource:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: MyFunctionName
      CodeUri: ./
      Handler: "lambda_function.lambda_handler"
      MemorySize: 128
      Runtime: python3.7
      Timeout: 3
      Policies:
        - Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action:
                - "cognito-idp:*"
                - "logs:*"
                ...
              Resource: "*"
## Remove this section
#       - Version: "2012-10-17"
#         Statement:
#           - Effect: Allow
#             Action: "lambda:InvokeFunction"
#             Principal:
#               Service: cognito-idp.amazonaws.com
#             Resource: !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:MyFunctionName"

## Add this instead
  MyFunctionPermissions:
    Type: AWS::Lambda::Permission
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt MyFunctionResource.Arn
      Principal: "cognito-idp.amazonaws.com"
      SourceArn: !Sub "arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/*"
于 2019-05-23T21:48:28.450 回答