Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use environment variable in github action if

I'm trying to use an environment variable in an if condition in github actions like so:

name: Worfklow
on:
  push

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1

      - name: EXIT step
        if: $GITHUB_REF == 'specific-branch'
        run: exit 1

I want to exit if the current branch is equal to a specific branch.

Unfortunately, the github actions console displays an error:

Unexpected symbol: '$GITHUB_REF'

I can use $GITHUB_REF in a run: (where it contains the current branch), but not in an if:. What am I doing wrong?

like image 795
Patrick Avatar asked Jan 23 '20 16:01

Patrick


People also ask

How do I pass an environment variable in GitHub Actions?

To set a custom environment variable, you must define it in the workflow file. The scope of a custom environment variable is limited to the element in which it is defined. You can define environment variables that are scoped for: The entire workflow, by using env at the top level of the workflow file.

How do I add an environment variable to GitHub?

To add a secret to your repository, go to your repository's Setting > Secrets , click on Add a new secret . In the screenshot below, I added 2 env variables: REACT_APP_APIKey and REACT_APP_APISecret . Notice: All the environment variable you want to access with create-react-app need to be prefixed with REACT_APP .

What is ref in GitHub Actions?

github.ref. string. The branch or tag ref that triggered the workflow run. For workflows triggered by push , this is the branch or tag ref that was pushed. For workflows triggered by pull_request , this is the pull request merge branch.


1 Answers

Though the original problem had been solved without environment vars, I'd like to share how it can be used with if conditions.

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:

      - name: Set env BRANCH
        run: echo "BRANCH=$(echo $GITHUB_REF | cut -d'/' -f 3)" >> $GITHUB_ENV

      - name: Set env NEED
        run: |
          if [[ $BRANCH == 'master' && $GITHUB_EVENT_NAME == 'push' ]]; then
              echo "NEED=true" >> "$GITHUB_ENV"
          else
              echo "NEED=false" >> "$GITHUB_ENV"
          fi

      - name: Skip Deploy?
        if: env.NEED != 'true'
        run: echo "Only pushing to 'master' causes automatic deployment"

     ...

The first two steps set 2 env variables, the third step demonstrates what syntax you need to follow to use these vars in if conditions.

like image 128
dhilt Avatar answered Sep 16 '22 17:09

dhilt