Skip to main content

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.1executors:
  basic:
    docker:
      - image: cimg/base:current
    resource_class: smalljobs:
  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 FOOworkflows:
  main:
    jobs:
      - create-env-var
      - load-env-var:
          requires:
            - create-env-var

Additional Resources:

Did this answer your question?