Reputation: 10349
I'm not able to access environment variables defined at the top-level of a GitHub Action configuration file from within a script run by the action.
For example, given the following config file:
name: x-pull-request
on: pull_request
env:
FOO: bar
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: does a thing
run: ./scripts/do-a-thing.sh
... and the following script:
X=${FOO:default}
echo "X: $X" # X: default
The FOO
environment variable defined in the config file is not available to the script and the default value is being used.
So, how can I access the environment variable from a Bash script run by the build step? Am I missing a prefix or something? (I know values defined in the input
hash require you to use an INPUT_
prefix when referencing them.)
Upvotes: 23
Views: 17666
Reputation: 2078
If you've to execute your script with sudo
privileges then make sure to use -E
flag so that sudo passes all envs to the script.
name: x-pull-request
on: pull_request
env:
FOO: bar
jobs:
test:
runs-on: ubuntu-latest
env:
SOME_ENV: some_val
steps:
- uses: actions/checkout@v1
- name: does a thing
run: sudo -E ./scripts/do-a-thing.sh
Upvotes: 0
Reputation: 476
I know this is old, but I came across this while writing my own GitHub Actions code and figured I'd point out what I believe is the actual issue you're running into.
The problem is you're using the wrong syntax for default variable values.
Incorrect:
myVal=${ENV_VAL:default}
Correct:
# Notice the addition of the hyphen
myVal=${ENV_VAL:-default}
Thus, your script should use:
X=${FOO:-default}
echo "X: $X" # X: default
More details can be found in the Parameter Expansion subsection of the docs.
Upvotes: 1
Reputation: 526
If some one else is searching for a solution you have to explicitly pass the environment variables to the bash script. Otherwise they are not available:
name: x-pull-request
on: pull_request
env:
FOO: bar
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: does a thing
run: ./scripts/do-a-thing.sh $FOO
and in the script you have to map the parameter to a variable.
X=$1
echo "X: $X" # X: default
Upvotes: 6
Reputation: 16740
You can use env at any level also in jobs and steps.
I wrote a test action and a test script to validate it:
The action file:
name: Env tests
on: push
env:
FOO_ROOT: bar on root
jobs:
test:
runs-on: ubuntu-latest
env:
FOO_JOB: bar on job
steps:
- uses: actions/checkout@v1
- name: Test envs
run: ./env-test.sh
env:
FOO_STEP: bar on step
The script file:
#!/usr/bin/env bash
echo "FOO_ROOT: $FOO_ROOT"
echo "FOO_JOB: $FOO_JOB"
echo "FOO_STEP: $FOO_STEP"
echo " "
printenv
The results:
FOO_ROOT: bar on root
FOO_JOB: bar on job
FOO_STEP: bar on step
LEIN_HOME=/usr/local/lib/lein
M2_HOME=/usr/share/apache-maven-3.6.3
...
Check my results and, in fact, I don't know why it didn't work on your side because it must work.
Upvotes: 9