在AWS SAM中使用!Ref设置环境变量吗?

Mah*_*hdi 2 amazon-web-services aws-cli aws-sam-cli aws-sam

我正在使用SAM CLI v0.8.1。我正在尝试将环境变量MY_TABLE_VAR设置为资源(MyTableResource)中表的名称。但是,在本地运行我的应用程序时,未定义MY_TABLE_VAR。您能告诉我模板中有什么问题吗,如何正确设置呢?以下是我的SAM模板:

Globals:
    Function:
        Timeout: 30
        Runtime: nodejs8.10        
        Environment:
            Variables:
                MY_TABLE_VAR: !Ref MyTableResource
Resources:
    MyTableResource:
        Type: AWS::Serverless::SimpleTable
        Properties:
          TableName: table1
          PrimaryKey:
            Name: id
            Type: String
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5
Run Code Online (Sandbox Code Playgroud)

mat*_*sev 6

从我的理解,该Globals部分不能引用资源的Resources部分(的依赖是在另一个方向,因为无论是添加到Globals添加节到所有无服务器功能和APIResources部分)。要解决此问题,建议您使用MappingsParameters,例如

Parameters:
    TableName:
        Type: String
        Default: table1

Globals:
    Function:
        Timeout: 30
        Runtime: nodejs8.10        
        Environment:
            Variables:
                MY_TABLE_VAR: !Ref TableName

Resources:
    MyTableResource:
        Type: AWS::Serverless::SimpleTable
        Properties:
          TableName: !Ref TableName
          # more table config....
Run Code Online (Sandbox Code Playgroud)