How to trigger a github workflow job only for specific branch using patterns

1k Views Asked by At

I would like to trigger a github action wf for a specific branch. My branch has the name

refs/heads/release/rc22-15.0.0

I would like to trigger the wf or a specific step for all releases refs/heads/release/**

The execution of the wf triggers both steps.

name: wf_logic_test_releasebranch

on:
  workflow_dispatch:

  push:
    branches:    
      - 'release/**'
      - 'feature/**'
      - 'main'


jobs:
  test_condition:
    name: job_test_condition
    runs-on: [atc-ubuntu-20.04]
    environment: sandbox


    steps:
      - name: Branch name   
        if: github.ref == 'refs/heads/release/rc22-15.0.0'
        run: echo running on branch ${GITHUB_REF##*/}

      - run: echo ${{github.ref}}

By changing the code to:

name: wf_logic_test_releasebranch

on:
  workflow_dispatch:

  push:
    branches:    
      - 'release/**'
      - 'feature/**'
      - 'main'


jobs:
  test_condition:
    name: job_test_condition
    runs-on: [atc-ubuntu-20.04]
    environment: sandbox


    steps:
      - name: Branch name   
        if: github.ref == 'refs/heads/release/**'
        run: echo running on branch ${GITHUB_REF##*/}

      - run: echo ${{github.ref}}

The execution of the above wf triggers only the second step.

1

There are 1 best solutions below

0
On

This is what worked for me:

name: wf_logic_test_releasebranch

on:
  workflow_dispatch:

  push:
    branches:    
      - 'release/**'
      - 'feature/**'
      - 'main'


jobs:
  test_condition:
    name: job_test_condition
    runs-on: [atc-ubuntu-20.04]
    environment: sandbox


    steps:
      - name: Always call branch name   
        run: echo running on branch ${GITHUB_REF##*/}

         #WF executes step only if branch name is main
      - name: Determine IP of runner only for release branch
        if: 
          contains(github.ref, 'release')
        run: curl https://api.ipify.org

      - name: Show branch name for main and feature branch only
        if:
          contains(github.ref, 'main') ||  contains(github.ref, 'feature')
        run: echo running on branch ${GITHUB_REF##*/}

  job_only_for_main:
    name: job_test_only_for_main
    runs-on: [atc-ubuntu-20.04]
    environment: sandbox
    if:
      contains(github.ref, 'main')

    steps:
      - name: Always call branch name   
        run: echo running on branch ${GITHUB_REF##*/}