8

我正在使用 AWS Textract,我想分析一个多页文档,因此我必须使用异步选项,所以我首先使用startDocumentAnalysis函数,我得到一个 JobId 作为返回,但它需要触发我设置的函数当 SNS 主题收到消息时触发。

这些是我的无服务器文件和处理程序文件。

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: us-east-1
  iamRoleStatements:
    - Effect: "Allow"
      Action:
       - "s3:*"
      Resource: { "Fn::Join": ["", ["arn:aws:s3:::${self:custom.secrets.IMAGE_BUCKET_NAME}", "/*" ] ] }
    - Effect: "Allow"
      Action:
        - "sts:AssumeRole"
        - "SNS:Publish"
        - "lambda:InvokeFunction"
        - "textract:DetectDocumentText"
        - "textract:AnalyzeDocument"
        - "textract:StartDocumentAnalysis"
        - "textract:GetDocumentAnalysis"
      Resource: "*"

custom:
  secrets: ${file(secrets.${opt:stage, self:provider.stage}.yml)}

functions:
  routes:
    handler: src/functions/routes/handler.run
    events:
      - s3:
          bucket: ${self:custom.secrets.IMAGE_BUCKET_NAME}
          event: s3:ObjectCreated:*

  textract:
    handler: src/functions/routes/handler.detectTextAnalysis
    events:
      - sns: "TextractTopic"

resources:
  Resources:
    TextractTopic:
        Type: AWS::SNS::Topic
        Properties:
          DisplayName: "Start Textract API Response"
          TopicName: TextractResponseTopic

处理程序.js

module.exports.run = async (event) => {
  const uploadedBucket = event.Records[0].s3.bucket.name;
  const uploadedObjetct = event.Records[0].s3.object.key;

  var params = {
    DocumentLocation: {
      S3Object: {
        Bucket: uploadedBucket,
        Name: uploadedObjetct
      }
    },
    FeatureTypes: [
      "TABLES", 
      "FORMS"
    ],
    NotificationChannel: {
      RoleArn: 'arn:aws:iam::<accont-id>:role/qvalia-ocr-solution-dev-us-east-1-lambdaRole', 
      SNSTopicArn: 'arn:aws:sns:us-east-1:<accont-id>:TextractTopic'
    }
  };

  let textractOutput = await new Promise((resolve, reject) => {
    textract.startDocumentAnalysis(params, function(err, data) {
      if (err) reject(err); 
      else resolve(data);
    });
  });
}

我手动向该主题发布了一条 sns 消息,然后它正在触发当前具有此功能的 textract lambda,

module.exports.detectTextAnalysis = async (event) => {
  console.log('SNS Topic isssss Generated');
  console.log(event.Records[0].Sns.Message);
};

我有什么错误以及为什么文本 startDocumentAnalysis 没有发布消息并使其触发 lambda?

注意:在使用 startTextAnalysis 函数之前,我没有使用 startDocumentTextDetection,尽管在此之前没有必要调用它。

4

5 回答 5

10

确保您在受信任的关系中拥有您正在使用的角色:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "lambda.amazonaws.com",
          "textract.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
于 2019-07-11T21:38:05.763 回答
2

SNS 主题名称必须是 AmazonTextract

最后你的 arn 应该是这样的:

arn:aws:sns:us-east-2:111111111111:AmazonTextract
于 2021-04-29T03:20:45.083 回答
0

serverless.yml通过将 Lambda 执行资源添加到我的文件中,我可以直接通过无服务器框架实现此功能:

resources:
  Resources:
    IamRoleLambdaExecution:
      Type: AWS::IAM::Role
      Properties:
        AssumeRolePolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
                  - textract.amazonaws.com
              Action: sts:AssumeRole

然后我只是在开始Textract文档分析时使用了Serverless生成的相同角色(用于lambda函数)作为通知通道角色参数:

感谢这篇文章为我指明了正确的方向!

于 2020-10-28T20:56:31.370 回答
0

对于在 TypeScript 中使用 CDK 的任何人,您都需要像往常一样将 Lambda 作为 ServicePrincipal 添加到 Lambda 执行角色。接下来,访问assumeRolePolicy执行角色并调用addStatements方法。

没有任何附加语句的基本执行角色(稍后添加)

  this.executionRole = new iam.Role(this, 'ExecutionRole', {
    assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
  });

接下来,将 Textract 添加为附加的 ServicePrincipal

  this.executionRole.assumeRolePolicy?.addStatements(
    new PolicyStatement({
      principals: [
        new ServicePrincipal('textract.amazonaws.com'),
      ],
      actions: ['sts:AssumeRole']
    })
  );

此外,确保执行角色对目标 SNS 主题具有完全权限(注意主题已创建并通过 fromTopicArn 方法访问)

 const stmtSNSOps = new PolicyStatement({
    effect: iam.Effect.ALLOW,
    actions: [
      "SNS:*"
    ],
    resources: [
      this.textractJobStatusTopic.topicArn
    ]
  });

将策略语句添加到全局策略(在活动堆栈内)

 this.standardPolicy = new iam.Policy(this, 'Policy', {
    statements: [
      ...
      stmtSNSOps, 
      ...
    ]
  });

最后,将策略附加到执行角色

  this.executionRole.attachInlinePolicy(this.standardPolicy);
于 2020-11-09T22:29:19.357 回答
-1

如果您的存储桶已加密,则应授予 kms 权限,否则将无法正常工作

于 2019-07-04T13:19:51.430 回答