I’ve got about 40 repos that run nearly the same basic Build & Test workflow, and I’d like to make it a reusable workflow.
name: Build & Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "20.x"
- name: Install dependencies
run: yarn
- name: Run tests
run: yarn test
The problem is, occasionally, it will depend on an ENV variable or two, like so:
- name: Run tests
env:
SOME_API_KEY: ${{ secrets.SOME_API_KEY }}
run: yarn test
Most of what I’ve seen is people passing required environment variables through the inputs
, but I haven’t been able to find any solutions for when you don’t know what those variables are going to be named, or if they even exist. I’ve tried using organization secrets with secrets: inherit
but that’s not really an optimal solution for a one-off API key that we only use in one repo.
This seemed promising but I couldn’t get it working with secrets.
Has anyone found a suitable workaround?
olive20xx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
To pass in a secret as an environment variable, you would have to do the following:
jobs:
my-job:
uses: ./.github/workflows/my-reusable-workflow.yml
with:
env_vars: |
env1=${{ secrets.SOME_API_KEY }}
env2=${{ secrets.SOME_API_KEY_2 }}
env3=${{ secrets.SOME_API_KEY_3 }}
This is a generic approach and does not require reusable workflow to known the names env1, env2, env3 in advance. These names can be any valid environment variable names.
You could even do something simpler:
jobs:
my-job:
uses: ./.github/workflows/my-reusable-workflow.yml
with:
env_vars: |
export env1=${{ secrets.SOME_API_KEY }}
export env2=${{ secrets.SOME_API_KEY_2 }}
export env3=${{ secrets.SOME_API_KEY_3 }}
Then inside the reusable workflow you would do this:
steps:
- run: |
# Inject environment vars
${{ inputs.env_vars }}
# Run any commands/shell scripts that need these variables