【问题标题】:set env variables in serverless framework conditionally有条件地在无服务器框架中设置环境变量
【发布时间】:2021-11-20 10:12:06
【问题描述】:

我正在尝试设置环境变量(称为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

【问题讨论】:

    标签: javascript aws-lambda serverless-framework


    【解决方案1】:

    我建议只使用 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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      相关资源
      最近更新 更多