Search code examples
javascriptaws-lambdaserverless-framework

set env variables in serverless framework conditionally


i am trying to set env variable ( called as baseUrl), however i want that variable value to change depending on the stage value.

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

here is my serverless.yml file

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

Solution

  • I would recommend simply using dotenv feature, which is described in the documentation: https://www.serverless.com/framework/docs/environment-variables/

    An example, how to do it

    Files structure:

    serverless.yml
    .env.dev
    .env.prod
    

    Files content:

    .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
    

    Then you can easily use it from custom section, as a normal Serverless Framework variable.