在 AWS CloudFormation 模板中引用 !Ref DynamoDB 表名称

McS*_*man 9 aws-cloudformation aws-sam

我正在尝试在本地测试传递我的 CloudFormation 模板文件中声明的 DynamoDB 表的表名。

从我阅读的所有文档中,我应该能够TableName使用!Ref内部函数引用DynamoDB 资源的属性值。但是,当我在本地测试时,该属性未定义。

考虑以下示例:

Transform: 'AWS::Serverless-2016-10-31'
Resources:
  ServerlessFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs10.x
      Handler: index.handler
      Environment: 
        Variables:
          TABLE_NAME: !Ref DynamoDBTable # <- returning undefined
      Events:
        GetCocktails:
          Type: Api
          Properties:
            Path: /
            Method: get
  DynamoDBTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: DynamoDBTableName
      AttributeDefinitions:
        - AttributeName: ID
          AttributeType: S
      KeySchema:
        - AttributeName: ID
          KeyType: HASH
      ProvisionedThroughput: 
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
Run Code Online (Sandbox Code Playgroud)

我希望TABLE_NAME环境变量是DynamoDBTableName但是它返回未定义。如何让模板按预期工作?

Lor*_*Goo 10

正如其他人所说,AWS::DynamoDB::Table 公开的唯一属性是: ArnStreamArn(请参阅AWS CloudFormation DynamoDB 文档)。

提供 DynamoDB 的语法,arn您可以通过以下方式检索表名:

      Environment: 
        Variables:
          TABLE_NAME: !Select [1, !Split ['/', !GetAtt DynamoDBTable.Arn]] 
Run Code Online (Sandbox Code Playgroud)

这将返回DynamoDBTableName

  • 您是正确的,公开的属性是 Arn 和 StreamArn。即调用 !GetAttr 但调用 !Ref 返回表名 (2认同)

小智 5

我也遇到了同样的问题,看起来您无法访问 TableName。

我正在做的解决方法是使用相同的表名调用 tamplate.yml 中的资源...

在模板.yml中:

Globals:
  Function:
    Runtime: nodejs12.x
    ...
    Environment:
      Variables:
        DYNAMODB_TABLE: !Ref MyDynamoTable
Run Code Online (Sandbox Code Playgroud)
MyDynamoTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: MyDynamoTable
      AttributeDefinitions:
        - AttributeName: PK
          AttributeType: S
        - AttributeName: SK
          AttributeType: S
Run Code Online (Sandbox Code Playgroud)

然后,在我的 .js 组件中:

const tableName = process.env.DYNAMODB_TABLE;
Run Code Online (Sandbox Code Playgroud)

我希望他们尽快解决这个问题......这种方式并不理想。干杯!


小智 -5

从您的资源返回!Ref DynamoDBTableARN 因此您将获得如下参考响应:

arn:aws:dynamodb:us-east-1:123456789012:table/testddbstack-myDynamoDBTable-012A1SL7SMP5Q/stream/2015-11-30T20:10:00.000

相反,您只需要提供名称DynamoDBTableName,因此我的建议是使用!GetAtt CloudFormation 内部函数并获取名称: !GetAtt DynamoDBTable.TableName