Search code examples
mavengithubconditional-statementsgithub-actionsworkflow

GitHub Actions restrict job with tag validation using if condition or github ref


I have an application code which runs the maven builds we created snapshots and then create a tag created once the snapshot build is successful, and then we use the tag created in the snapshot build and then run the build using the tag for release using the GitHub actions workflows. now I'm trying to run the release of the build workflow job only if the tag as matching and if the tag, not matches, skip the jobs or fails the jobs, let's say the tag will be created in the snapshot build and will use tag format as "<appname>-<app_build_type>-<github-actions-run_number>-<env>-origin/<branch>" and the actual tag looks like "java-maven-44-dev-origin/develop" I was trying the below 2 methods workflows, but it is not at all working 1st Method is:

name: maven-release

on:
  workflow_dispatch:

jobs:
  checkout_code:
    runs-on: [ubuntu-latest]
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

  maven_build:
    runs-on: [ubuntu-latest]
    if: ${{ github.ref == 'refs/tags/*-origin/develop' }}
    needs: checkout_code
    steps:
      - name: Run maven build
        run: |
          mvn clean install

2nd Method is:

name: maven-release

on:
  workflow_dispatch:

jobs:
  checkout_code:
    runs-on: [ubuntu-latest]
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

  maven_build:
    runs-on: [ubuntu-latest]
    if: contains(github.ref, 'refs/tags/*-origin/develop')
    needs: checkout_code
    steps:
      - name: Run maven build
        run: |
          mvn clean install

I want to skip/fail the at job level only and no in run command, if anyone knows any solution to this or anyone can provide some suggestions on how to achieve this


Solution

  • For the workflows for which each task needs to be executed only on a particular tag, then we can make use of below snipped

    name: maven_build
    on:
      workflow_dispatch:
    jobs:
      checkout:
        runs-on: [ubuntu-latest]
        steps:
          - name: Checkout
            uses: actions/checkout@v3
            with:
              fetch-depth: 0
      maven_build:
        runs-on: [ubuntu-latest]
        if: startsWith(github.ref, 'refs/tags/') && !contains(github.ref')
        needs: checkout
        steps:
          - name: Run maven build command
            run: |
              mvn clean install
    

    The above snippet will run only when the checkout branch matches a tag