Serverless 1.2 Setting Environment Variables and Nested Variables

That makes this a lot easier to answer and gives your more options.

If you only want to prefix table names with the stage you can do something like:

custom:
  stage: "${opt:stage, self:provider.stage}"
  myTable: "${self:custom.stage}-my-table"

provider:
  environment:
    MY_TABLE: "${self:custom.myTable}"

resources:
  Resources:
    MyTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.myTable}

Inside your code use process.env.MY_TABLE to reference the correct table.

At some point you’ll probably end up with environment variable that can’t simply be prefixed (API keys or username/password for example). When that happens you can put this into serverless.yml

custom:
  stage: "${opt:stage, self:provider.stage}"
  myTable: "${self:custom.stage}-my-table"

provider:
  environment: ${file(env.yml):${self:custom.stage}}

resources:
  Resources:
    MyTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.myTable}

Then inside your env.yml put:

dev:
  MY_TABLE: "${self:custom.myTable}"
  API_KEY: "Development API key"

prod:
  MY_TABLE: "${self:custom.myTable}"
  API_KEY: "Production API key"

I’ve got a more detailed write-up of this at Using Environment Variables with the Serverless Framework. I’ll update it in the next day to better cover your scenario.

3 Likes