Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional "needs" in GitHub Actions?

I have a GitHub workflow that looks like this:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "build"

  test:
    runs-on: ubuntu-latest
    needs: build

    steps:
      - run: echo "build"

  deploy:
    runs-on: ubuntu-latest
    needs: [build, test]

    steps:
      - run: echo "deploy"

Now, I'd like to make it so that the deploy step only needs the tests step if the branch is main.

Is that possible?

Essentially I'd love to do something like this:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "build"

  test:
    runs-on: ubuntu-latest
    needs: build

    steps:
      - run: echo "build"

  deploy:
    runs-on: ubuntu-latest
    needs: contains(branch, "master") ? [build, test] : [build] #notice this line

    steps:
      - run: echo "deploy"
like image 854
Mathias Lykkegaard Lorenzen Avatar asked Sep 04 '25 17:09

Mathias Lykkegaard Lorenzen


1 Answers

GitHub action isn't allowing conditional needs (unfortunately, imho).

Yet, there is a workaround: Make your jobs run sequentially by defining the prerequisites in needs. All jobs required to run no matter what happened to the prerequisites need get the if condition set to always().

If a failure of a previous job is supposed to kill you need to add a step for verifying the job result(s).

This is an general solution for adaption:

jobs:
  init_job:
    runs-on: ubuntu-latest
    steps:
      - run: echo "initial run"

  conditional_job:
    runs-on: ubuntu-latest
    needs: init_job
    if: ${{ your condition here }}
    steps:
      - run: echo "conditonal run"

  final_job:
    needs: conditional_job
    if: always()
    steps:
      - name: fail if conditional job failed
        if: ${{ needs.conditional_job.result == 'failure' }}
        run: exit 1
      - run: echo "final run"

like image 66
Janluak Avatar answered Sep 06 '25 14:09

Janluak