Share environment variable between different job

I’m trying to pass an environment variable value from one job to another in the following way

  - run:
      command: |
          echo 'export MY_ENV_VAR="FOO"' >> "$BASH_ENV"
  - run:
      command: |
          echo ${MY_ENV_VAR}

All I’m getting is an empty line
What am I doing wrong?

from one job to another

It would be helpful to see your entire config, but in general this approach only works for steps inside of the same job. There is no way to share environment variables like this between jobs.

You can see this part of the docs for more info: https://circleci.com/docs/env-vars#using-parameters-and-bash-environment

That what I was suspecting. Thanks!

As @levlaz shared, there is no real built-in feature to share env variables between jobs.

However, if the 2 jobs are in the same workflow (e.g., job A → job B), then you can take advantage of workspaces to pass and load the $BASH_ENV file.

As an example, you can do something like this:

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: |
          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: |
          printenv FOO

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

Ref:

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.