Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger github workflow only if pushed to specific branch and tag exists

I want to trigger a Github workflow only if a code is pushed to a specific branch and if a tag exists, but my config (github workflow) does not work as expected:

name: Deployment
on:
  push:
    branches:
      - feature/BRANCH-NAME
    tags:
      - *
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1
      - uses: actions/setup-node@v1
        with:
          node-version: '10.x'

      - name: Install dependencies
        run: |
          npm install

      - name: Lint & build
        run: |
          npm run build

The workflow is triggered even if a tag does not exist.

How could I fix this?

like image 301
Patrick Avatar asked Sep 03 '25 04:09

Patrick


2 Answers

EDIT: This workaround seemed to have solved my problem at the time of writing but I cannot guarantee that it still works as expected.


Since I couldn't find a way to implement an AND condition (i.e. tagged AND on master), I used the following workaround:

name: Worflow demo
on:
  push:
    tags:
      - v*

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

      - name: Exit if not on master branch
        if: endsWith(github.ref, 'master') == false
        run: exit -1
      
      - name: Next job ...

This will trigger if there is a tagged (e.g. tag v1.0.0) commit pushed:

on:
  push:
    tags:
      - v*

The first step ('Exit if not on master branch') then checks if the current branch doesn't end with master and exits the workflow (the subsequent tests will not start):

- name: Exit if not on master branch
  if: endsWith(github.ref, 'master') == false
  run: exit -1

Hope this helps someone else as well.

like image 199
Patrick Avatar answered Sep 05 '25 01:09

Patrick


The accepted answer didn't seem to work for me, as pointed out by dilithiummatrix in the comments.

So I tried outputting the available values of the github object, which you can do by adding this in your workflow file to see what is available:

      - name: Dump job github var
        env:
          GITHUB_VAR: ${{ toJson(github) }}
        run: echo "$GITHUB_VAR"

From this I noticed that as Billy Clark also pointed out, that github.event.base_ref contains refs/heads/production. So this worked for me:

      # Only release from prod branch
      - name: Exit if not on production branch
        if: endsWith(github.event.base_ref, 'production') == false
        run: exit -1
like image 31
Vasco Avatar answered Sep 04 '25 23:09

Vasco