You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS CloudFormation !Ref函数用法及SAM模板表名引用异常解决

在AWS SAM/CloudFormation中正确引用DynamoDB物理表名的方法

一、!Ref函数在CloudFormation里的行为逻辑

!Ref是CloudFormation的核心引用函数,但它返回的值并非对所有资源都是物理ID:

  • 对EC2实例、S3桶这类资源,!Ref返回的是实际物理标识(比如i-xxxxxx、my-bucket-123)
  • 但对DynamoDB表(不管是原生CloudFormation的AWS::DynamoDB::Table还是SAM的AWS::Serverless::Table),!Ref默认返回的是模板里定义的逻辑名(比如你写的SampleTable),而非带堆栈前缀和随机后缀的物理表名——这就是你Lambda报错“Table resource not found”的直接原因。

二、SAM模板里正确获取物理表名的方法

要拿到DynamoDB的实际物理表名,得用!GetAtt函数,直接读取表资源的TableName属性。

错误写法(返回逻辑名)

Resources:
  SampleTable:
    Type: AWS::DynamoDB::Table
    Properties:
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
  MyLambda:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.11
      Handler: app.lambda_handler
      Environment:
        Variables:
          SAMPLE_TABLE: !Ref SampleTable  # 这里得到的是逻辑名SampleTable

正确写法(返回物理表名)

Resources:
  SampleTable:
    Type: AWS::DynamoDB::Table
    Properties:
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
  MyLambda:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.11
      Handler: app.lambda_handler
      Environment:
        Variables:
          SAMPLE_TABLE: !GetAtt SampleTable.TableName  # 这里得到的是实际物理表名,比如eliaTst-SampleTable-OFRSBK12RIQV

补充:用SAM的Serverless::Table也是同样逻辑

如果你的表是用SAM简化的AWS::Serverless::Table定义的,同样不能用!Ref获取物理名,必须用!GetAtt:

Resources:
  SampleTable:
    Type: AWS::Serverless::Table
    Properties:
      PrimaryKey:
        Name: id
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
  MyLambda:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.11
      Handler: app.lambda_handler
      Environment:
        Variables:
          SAMPLE_TABLE: !GetAtt SampleTable.TableName

内容的提问来源于stack exchange,提问作者Elia Weiss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:50:52