Recently I have been working with GitHub Actions and needed to be able to share environment variables across different GitHub workflows, to which I discovered that this feature doesn’t currently exist. As an alternative you can set variables as secrets in your GitHub repository, although that is quite manual and doesn’t help if you would like to manage variables in code.
We can solve this by storing our environment variables in a .env file and utilise a GitHub Action to configure variables for our GitHub workflows.
A GitHub Action has been published on the GitHub Actions Marketplace (available here) to help you achieve this or alternatively if you would like to utilise your own custom GitHub Action, follow the steps below.
1. Create a custom GitHub Action to set environment variables based off a file
action.yml
name: 'Set environment variables'
description: 'Configures environment variables for a workflow'
inputs:
varFilePath:
description: 'File path to variable file or directory. Defaults to ./.github/variables/* if none specified and runs against each file in that directory.'
required: false
default: ./.github/variables/*
runs:
using: "composite"
steps:
- run: |
sed "" ${{ inputs.varFilePath }} >> $GITHUB_ENV
shell: bash
2. Create .env file containing your variables and values
myvars.env
MYVAR1=value1
MYVAR2=value2
3. Add step in your GitHub Workflow to set environment variables
myworkflow.yml
deploy:
if: ${{ github.ref == 'refs/heads/master' }}
needs: build
runs-on: ubuntu-latest
steps:
- name: Set Environment Variables
uses: ./.github/actions/setvars
with:
varFilePath: ./.github/variables/myvars.env
That’s it! Our GitHub Workflow will now use variables from our .env file which we can manage in code and reuse in other GitHub Workflows.
For reference my repo structure is as follows.
├── .github/
| ├── actions/
| | ├── setvars/
| | | ├── action.yml
| ├── variables/
| | ├── myvars.env
| ├── workflows/
| | ├── myworkflow.yml