使用无服务器框架创建的 DynamoDB table 名称具有随机后缀

DynamoDB table name created with the serverless framework has a random suffix

我正在使用无服务器框架创建 DynamoDB table,然后我想从 Lambda 函数访问它。

serverless.yml 文件中,我对环境变量和 CF 资源进行了以下定义。

我期待的是一个名为 accounts-api-dev-accounts 的 table,但 cloudformation 堆栈为我创建的是 accounts-api-dev-accounts-SOME_RANDOM_LETTERS_AND_NUMBERS_SUFFIX

在我的 lambda 函数中,环境变量 DYNAMODB_ACCOUNTS_TABLE_NAME 暴露给没有 SOME_RANDOM_LETTERS_AND_NUMBERS_SUFFIX 部分的函数。 CF 堆栈是否应该添加随机后缀?我如何真正检索到正确的 table 名称?

service:
  name: accounts-api
provider:
...
  stage: ${opt:stage, 'dev'}
  environment:
    DYNAMODB_ACCOUNTS_TABLE_NAME: '${self:service}-${self:provider.stage}-accounts'

以及以下 CF 资源:

  Resources:
      AccountsTable:
          Type: AWS::DynamoDB::Table
          Properties:
            TableName: ${env:DYNAMODB_ACCOUNTS_TABLE_NAME}
            AttributeDefinitions:
              - AttributeName: customerNumber
                AttributeType: S
              - AttributeName: accountNumber
                AttributeType: S
            KeySchema:
              - AttributeName: customerNumber
                KeyType: HASH
              - AttributeName: accountNumber
                KeyType: RANGE
            ProvisionedThroughput:
              ReadCapacityUnits: 1
              WriteCapacityUnits: 1

可能在创建 table 定义时环境变量尚未更新?我不确定。

尝试 ${self:provider.environment.DYNAMODB_ACCOUNTS_TABLE_NAME} 而不是 ${env:DYNAMODB_ACCOUNTS_TABLE_NAME}

我还没有看到这种行为(部署后的随机字符),当 table 必须被替换时,它可能是一种强制唯一性的方法。您可以使用另一个环境变量并让 Table 资源的输出填充值。这样,CloudFormation 会将实际资源名称注入 Lambda 环境变量。我没试过这个,但这将是我第一次“去”。

environment:
  DYNAMODB_ACCOUNTS_TABLE_NAME: '${self:service}-${self:provider.stage}-accounts'
  ACTUAL_DYNAMODB_ACCOUNTS_TABLE_NAME:
    Ref: AccountsTable