Environment Variables + Bitbucket Pipelines + Serverless Deployment

Julia N.
2 min readJan 16, 2020

--

I finally got Bitbucket pipelines working with my Serverless setup. I was having trouble getting my build to properly access environment variables I had defined, but now that I’ve figured it out, it seems so obvious. D’oh.

The solution was that I had to declare the environment variables in my serverless.yml file in addition to my bitbucket-pipelines.yml file. If you’re running into the same issues, here are the steps to get it working:

  1. Go to your repository settings.
  2. Scroll down to the section for Pipelines and click on Repository Variables. Alternatively, you can define variables for specific environments by clicking on Deployments and declaring them there.
  3. Declare the variables you set up on Bitbucket in your bitbucket-pipelines.yml file.
  4. Declare the variables from your bitbucket-pipelines.yml file in your serverless.yml file so that it can be exposed to your application.

Example bitbucket-pipelines.yml file:

definitions:
steps:
- step: &build-deploy
name: Build & Deploy to Test
deployment: Test
caches:
- node
script:
- yarn
- pipe: atlassian/serverless-deploy:0.1.2
variables:
AWS_ACCESS_KEY: $KEY_DEFINED_ON_BITBUCKET
AWS_SECRET_ACCESS_KEY: $SECRET_DEFINED_ON_BITBUCKET
SERVERLESS_ACCESS_KEY: $SAK_DEFINED_ON_BITBUCKET
EXTRA_ARGS: "--stage $STAGE_DEFINED_ON_BITBUCKET"

pipelines:
branches:
develop:
- step: *build-deploy
master:
- step:
<<: *build-deploy
name: Build & Deploy to Prod
deployment: Production

Note: In the above example, I am defining a reusable step under definitions with a YAML anchor for use in the pipelines section.

Example function definition in a serverless.yml file:

functions:
api:
handler: handler.api
events:
- http:
path: v1
method: get
environment:
SECRET_AWS_ACCESS_KEY: ${env:AWS_ACCESS_KEY}
SECRET_AWS_SECRET_ACCESS_KEY: ${env:AWS_SECRET_ACCESS_KEY}

Now, in my Node application code, I can reference those environment variables as usual with process.env.SECRET_AWS_ACCESS_KEY

tl;dr

  1. Define your environment variables on Bitbucket.
  2. Declare them in bitbucket-pipelines.yml
  3. Declare them in serverless.yml
  4. Access them via process.env.VARIABLE_NAME

--

--