有条件地在无服务器框架中设置环境变量

set env variables in serverless framework conditionally

我正在尝试设置环境变量(称为 baseUrl),但是我希望该变量值根据阶段值而改变。

for example if stage = dev baseurl= https://example.com
for exma[le if stage = prod baseurl= https://example2.com

这是我的 serverless.yml 文件

custom:
  profiles:
    dev: default
    prod: mad

provider:
  name: aws
  profile: ${self:custom.profiles.${sls:stage}}
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  region: ap-southeast-1
  iam:
    role:
      statements:
        - Effect: Allow
          Action:
            - dynamodb:DescribeTable
            - dynamodb:Query
            - dynamodb:Scan
            - dynamodb:GetItem
            - dynamodb:PutItem
            - dynamodb:UpdateItem
            - dynamodb:DeleteItem
          Resource: arn:aws:dynamodb:ap-southeast-1::

resources:
  Resources:
    trimifyUrlsTable:
      Type: 'AWS::DynamoDB::Table'
      Properties:
        AttributeDefinitions:
          - AttributeName: pk
            AttributeType: S
          - AttributeName: originalUrl
            AttributeType: S
        KeySchema:
          - AttributeName: pk
            KeyType: HASH
          - AttributeName: originalUrl
            KeyType: RANGE
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: 'mad_dove_urls'

functions:
  customAuthorizer:
    handler: authorizer/authorizer.auth
    environment:
      ACCOUNT_ID: ${aws:accountId}
      API_ENDPOINT:
         Ref: ApiGatewayRestApi
      STAGE_NAME: ${opt:stage, 'dev'}
  operations:
    handler: serverless.handler
    environment:
      STAGE_NAME: ${opt:stage, 'dev'}
    events:
      - http:
          path: /
          method: ANY
          cors: true
      - http:
          path: /{proxy+}
          method: ANY
          cors: true
      - http:
          path: /auth-ops
          method: ANY
          authorizer: customAuthorizer
          cors: true
      - http:
          path: /auth-ops/{proxy+}
          method: ANY
          authorizer: customAuthorizer
          cors: true

我建议只使用文档中描述的 dotenv 功能: https://www.serverless.com/framework/docs/environment-variables/

一个例子,怎么做

文件结构:

serverless.yml
.env.dev
.env.prod

文件内容:

.env.dev:

BASE_URL=https://example.com

.env.prod:

BASE_URL=https://example2.com

serverless.yml:

service: example-service

custom:
  profiles: ${env:BASE_URL} # this will be example/example2.com depends on the current stage

然后您可以从自定义部分轻松使用它,作为普通的无服务器框架变量。