【问题标题】:Setting environmental variables with !Ref in AWS SAM?在 AWS SAM 中使用 !Ref 设置环境变量?
【发布时间】:2019-05-10 20:30:04
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: amazon-web-services aws-cli aws-sam-cli aws-sam


    【解决方案1】:

    据我了解,Globals 部分不能引用 Resources 部分中的资源(依赖关系在另一个方向,因为添加到 Globals 部分的任何内容都会在 to all Serverless Functions and APIs 中添加 Resources部分)。为了解决这个问题,我建议您使用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....
    

    【讨论】:

    • 这是不正确的,Globals CAN 参考资源在Resources 部分,但(可能)不是所有类型。我设法声明了一个AWS::Serverless::LayerVersion 资源对象并在Globals: Function 范围内设置了Layers 属性,尽管该层是在Resources 部分内创建的。
    猜你喜欢
    • 2020-03-22
    • 2018-06-14
    • 2017-10-31
    • 2018-12-16
    • 2016-01-26
    • 2021-03-24
    • 2018-11-13
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多