How to pass environment variables between jobs

Overview

You can pass environment variables (env vars) between jobs via workspaces. In this article, we will showcase how to do so with a sample configuration.

 

Prerequisites

Workspaces can only be shared between jobs in the same workflow.

The solution requires an execution environment with Bash available, as we rely on the BASH_ENV environment variable.

 

Sample Configuration

version: 2.1

executors:
  basic:
    docker:
      - image: cimg/base:current
    resource_class: small

jobs:
  create-env-var:
    executor: basic
    steps:
      - run: |
          echo "export FOO=BAR" >> $BASH_ENV
      - run: |
          # verify; optional step
          printenv FOO
      - run: |
          cp $BASH_ENV bash.env
      - persist_to_workspace:
          root: .
          paths:
            - bash.env
  load-env-var:
    executor: basic
    steps:
      - attach_workspace:
          at: .
      - run: |
          cat bash.env >> $BASH_ENV
      - run: |
          # verify; this should print 'BAR'
          printenv FOO

workflows:
  main:
    jobs:
      - create-env-var
      - load-env-var:
          requires:
            - create-env-var

 

Additional Resources:

Was this article helpful?
7 out of 20 found this helpful

Comments

0 comments

Article is closed for comments.