Environment Variables + Bitbucket Pipelines + Serverless Deployment
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:
- Go to your repository settings.
- 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.
- Declare the variables you set up on Bitbucket in your
bitbucket-pipelines.yml
file. - Declare the variables from your
bitbucket-pipelines.yml
file in yourserverless.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
- Define your environment variables on Bitbucket.
- Declare them in
bitbucket-pipelines.yml
- Declare them in
serverless.yml
- Access them via
process.env.VARIABLE_NAME