Setting environmental variables with !Ref in AWS SAM?

落爺英雄遲暮 提交于 2020-02-04 11:00:44

问题


I'm using SAM CLI v0.8.1. I'm trying to set environmental variable MY_TABLE_VAR as name of the table in my resources (MyTableResource). However, while running my app locally, the MY_TABLE_VAR is undefined. Can you tell me what's wrong in my template and how can I set it properly? Following is my SAM template:

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

回答1:


From my understanding, the Globals section cannot reference resources in the Resources section (the dependency is in the other direction, since whatever is added to the Globals section is added to all Serverless Functions and APIs in the Resourcessection). To work around this, I suggest that you use either Mappings or Parameters, e.g.

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....


来源:https://stackoverflow.com/questions/53697215/setting-environmental-variables-with-ref-in-aws-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!