How to Pass Environment Variables Between Steps in CircleCI
Overview
Passing environment variables from one step to another within the same CircleCI job requires using the $BASH_ENV file. Since each run step in CircleCI starts a new shell session, variables set in one step are not automatically available in subsequent steps. By appending your variable export to $BASH_ENV, the variable will be sourced and available in all following steps within the same job.
Using BASH_ENV to Share Variables Between Steps
Basic Implementation
To pass an environment variable from one step to another, append your variable export to the $BASH_ENV file in the step where you set the variable:
jobs:
example-job:
docker:
- image: cimg/base:current
steps:
- run:
name: Set environment variable
command: echo 'export MY_VAR="foo"' >> $BASH_ENV
- run:
name: Use environment variable
command: echo $MY_VARIn this example, MY_VAR is set in the first step and becomes available in the second step because it was exported to $BASH_ENV.
How It Works
The $BASH_ENV file is automatically sourced at the beginning of each subsequent step within the same job. When you append your variable export to this file, CircleCI ensures the variable is available in the environment for all following steps.
Multiple Variables
You can set multiple environment variables by appending multiple export statements:
- run:
name: Set multiple environment variables
command: |
echo 'export VAR1="value1"' >> $BASH_ENV
echo 'export VAR2="value2"' >> $BASH_ENV
echo 'export VAR3="value3"' >> $BASH_ENVKey Implementation Points
Always Use Append Operation: Use the >> operator to append to $BASH_ENV rather than overwriting it. This ensures you don't accidentally remove other environment variables that CircleCI may have set.
Variable Availability: Once exported to $BASH_ENV, the variable will be available in all subsequent steps of the same job, but not in previous steps or other jobs.
Shell Session Isolation: Remember that each run step starts a fresh shell session, which is why standard variable assignment doesn't persist between steps.
Additional Notes
Cross-Job Variable Passing: If you need to pass environment variables between different jobs in your workflow, you must use workspaces to persist and restore the environment file. The $BASH_ENV approach only works within the same job.
Variable Scope: Variables set using $BASH_ENV are only available within the job where they are set. They do not persist across job boundaries or workflow runs.
Best Practices: Consider using descriptive variable names and documenting your environment variable usage in your workflow configuration for better maintainability.
Comments
Article is closed for comments.