AWS SAM YAML - 多次附加相同的策略,或在相同的 DynamoDB 策略上附加多个表

AWS SAM YAML - Attach same policy multiple times, or multiple tables on same DynamoDB policy

无法让角色访问两个表。 template.yaml:

的示例 YAML
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: path/to/something
      Handler: index.handler
      Runtime: nodejs10.x
      Events:
        Get:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /path/to/other/thing
            Method: post
      Policies:
        DynamoDBCrudPolicy:
          TableName:
            table1
            table2

我需要此函数才能在 table1 和 table2 上 read/write,但这不起作用。我试过了:

- table1
- table2

但这也不管用。也试过:

Policies:
  - DynamoDBCrudPolicy:
    TableName:
      table1
  - DynamoDBCrudPolicy:
    TableName:
      table2

但是那也出错了。我该如何正确执行此操作?

你有什么错误?看起来你错过了 TableName 的缩进,试试这个:

Policies:
 - DynamoDBCrudPolicy: 
     TableName: table1
 - DynamoDBCrudPolicy: 
     TableName: table2

PS:我本可以将其写入评论,但代码格式不正确

我会做的是为您的 lambda 函数创建一个角色,如下所示:

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: path/to/something
      Handler: index.handler
      Runtime: nodejs10.x
      Events:
        Get:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /path/to/other/thing
            Method: post
      Role: !GetAtt MyDynamoDBRole.Arn

然后将策略附加到该角色。像这样:

  MyDynamoDBRole:    
    Type: AWS::IAM::Role
    Properties:
      Path: "/"
      Policies:
        -
          PolicyName: "myDynamoDBPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: "Allow"
                Action:
                  - "dynamodb:BatchGetItem"
                  - "dynamodb:BatchWriteItem"
                  - "dynamodb:PutItem"
                  - "dynamodb:GetItem"
                  - "dynamodb:Scan"
                  - "dynamodb:Query"
                  - "dynamodb:UpdateItem"
                  - "dynamodb:UpdateTable"
                  - "dynamodb:GetRecords"
                Resource: "arn:aws:dynamodb:us-east-1:123456789012:table/table1"
      AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
          -
            Effect: Allow
            Principal:
              Service:
              - dynamodb.amazonaws.com
            Action: sts:AssumeRole

请注意:您可能需要调整特定权限以适合您的用例,上面的代码只是一个示例,用于说明我建议的结构。