0

I've created a GitHub repo which has GitHub Actions workflow. In the workflow I am executing a bash script which checks if it is being executed in the Actions workflow or not, once with user privileges, once with sudo privileges. The script checks if the GITHUB_ACTIONS env var is set or not.
The env var is set in the GH Actions workflow by default as stated in the GH Actions Documentation here.

The problem is that the script executed as sudo results in wrong behavior because GITHUB_ACTIONS variable is not set. Below is the explanation.

To recreate the issue, I've created GitHub Actions workflow which echoes if the GITHUB_ACTIONS env var is true or not. The workflow config file blank.yml is written below:

name: CI

on: [workflow_dispatch, push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    
    - name: Run as user
      run: bash test.sh
      
    - name: Run as root
      run: sudo bash test.sh

In one build step I am running a shell script test.sh as sudo, and in other as a "regular" user. test.sh is written as:

#!/bin/bash

if [[ ${GITHUB_ACTIONS=} == "true" ]]; then
    echo "GITHUB_ACTIONS env var is true."
else
    echo "GITHUB_ACTIONS env var is false."
fi

One would expect that the workflow would echo GITHUB_ACTIONS env var is true. in both build steps but the behavior is different. See a raw workflow log below:

##[group]Run bash test.sh
[36;1mbash test.sh[0m
shell: /usr/bin/bash -e {0}
##[endgroup]
GITHUB_ACTIONS env var is true.
##[group]Run sudo bash test.sh
[36;1msudo bash test.sh[0m
shell: /usr/bin/bash -e {0}
##[endgroup]
GITHUB_ACTIONS env var is false.

As you can see in the logs, bash test.sh run results in GITHUB_ACTIONS env var is true. and sudo bash test.sh in GITHUB_ACTIONS env var is false..

To check if the GITHUB_ACTIONS is even defined, I've created another bash script which checks for GITHUB_ACTIONS variable and echoes if it exist:

#!/bin/bash

if [[ -z "${GITHUB_ACTIONS}" ]]; then
  echo "GITHUB_ACTIONS variable is undefined."
fi

I've executed it with sudo privileges in the GH Actions workflow and indeed the var is undefined because GITHUB_ACTIONS variable is undefined. is echoed.
Everything is tested in this repo which you can fork and try for yourself.

Ivan Vnucec
  • 389
  • 2
  • 12
  • 1
    So what is your question? No worries, all is fine, this is expected. You can try locally, like `export a=1; sudo bash -c 'echo $a'`. – KamilCuk Mar 11 '22 at 08:53

0 Answers0