如何在云形成模板中根据阶段设置环境变量

问题描述

lambda 处理程序中的环境变量必须根据阶段通过 lambda 处理程序设置。 schema、endpoint 的值在不同的阶段是不同的。如何通过 yml 模板完成此操作。我是新手,所以不知道这将如何完成。

Parameters:
   Stage: {Type: String,Default: ''}
Resources:
   LambdaHandler:
   Type: AWS::Serverless::Function
   Properties:
       Environment:
          Variables:
          ......
          ......

如何继续?

解决方法

我想应该是:

Environment:
        Variables:
          your-key: !Ref Stage
,

您可以像下面那样使用 conditions

MyNotCondition:
  !Not [!Equals [!Ref EnvironmentType,prod]]
,

template.yaml:

Parameters:
  Environment:
    AllowedValues:
      - dev
      - prod
    Type: String

Resources:
  myLambda:
    Properties:
      Environment:
        Variables:
          stage: !Ref Environment

你的外壳:

$ aws cloudformation deploy --parameter-overrides Environment=dev

假设你想要一个以环境为条件的变量:

Parameters:
    Environment:
        AllowedValues:
            - dev
            - prod
        Type: String

Mappings:
    Environments:
        dev:
            LogLevel: "DEBUG"
        prod:
            LogLevel: "ERROR"

Resources:
    myLambda:
        Type: AWS::Lambda::Function
        Properties:
            Environment:
                Variables:
                    LOG_LEVEL: !FindInMap [Environments,!Ref Environment,LogLevel]
,

看看这篇关于如何使用阶段参数和使用映射来设置环境变量的文章 https://www.singlestoneconsulting.com/blog/cloudformation-mapping-and-conditionals-making-your-templates-more-universal/