Make stageVariables clear

Please don’t simply refer me to the documentation. I have read it. If it was clear, I wouldn’t be writing this post.

I understand that serverless has deemed amazon’s way of doing stageVariables as not preferred. That is fine with me. However, if there is not going to be support for the feature as designed by AWS, then please provide a clear and concise explanation of how you would like it to be done. Not an explanation that is mixed in with several other use cases that simply cloud the process. Specifically, what is the desired way you want me to handle stageVariables using serverless? I have drilled through the GitHub conversations and other posts, but it is difficult to determine what, in the end, is the solution (if any).

I have hundreds of endpoints to convert to serverless (maybe), and I really need this feature nailed down before I do anything.

There are two ways you can handle with this. Inside serverless.yml you’ll want to add a custom stage variable to make it easy to reference the stage you’re deploying to.

  stage: "${opt:stage, self:provider.stage}"

If you want single env file then create env.yml with a section for each stage and the environment variables below it. For example:

  MY_VAR: 'the dev value'

  MY_VAR: 'the prod value'

Then setup the environment variables inside your serverless.yml using

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

If you want one file per env then create env-STAGE.yml (i.e. env-dev.yml, env-prod.yml, etc). Each file should look like:

MY_VAR: 'the value'

The setup the environment variables inside your serverless.yml so that it uses the correct file.

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

You’ll probably want to add your env file to the .gitignore.

I guess where I get confused is how to use the environment variables in code. I can’t find any explanation in the documentation. If I google it, I get lots of stuff from earlier versions of serverless, but the latest version (>=1.0) is so widely different that none of the examples I could find apply. Even in the current documentation it talks about using “env:”, but you mention “environment”:, and no where in the documentation are there any code examples (I’d prefer nodeJS examples, but anything would be great).

How do I access the variables, in code, I define in serverless.yml?

ok feeling a little stupid. I think I figured out why the documentation talks about “env:” and you talk about “environment:”. “environment:” is used to configure the new environment variables feature of lambda functions.

@shawnmullen Correct. You use environment inside your serverless.yml that setups and the variables and env inside your code (if you’re using Node).

I’ve written a post Using Environment Variables with the Serverless Framework which explains this in a little more detail.