Bashscript on ci workflow
Programming

Build the production image only when the release tag is published from the master branch using Github Action

Many times the developer might publish the release tag from another branch and release it in the production. This is not good practice. Also, since the branch and tag are different things and it is not possible to know from which branch the tag is published, it is difficult to write the CI actions that will restrict the user to do so.
The solution is to trigger the GitHub action only when the release tag is published and then compare the commit hash with that of the master branch. This is because the tag will have the same commit hash as that of the branch from which the tag is published.
name: Check Deployment and versions
on:
  push:
    tags:
      - v1.*
jobs:
  check-tag-branch:
    runs-on: ubuntu-latest
    steps:
    - name: get tag commit hash
      id: tag-commit-hash
      run: |
        hash=${{ GITHUB.SHA }}
        echo "::set-output name=tag-hash::${hash}"
    - name: checkout master
      uses: actions/checkout@v2
      with:
        ref: master
    - name: get latest master commit hash
      id: master-commit-hash
      run: |
        hash=$(git log -n1 --format=format:"%H")
        echo "::set-output name=master-hash::${hash}"
    - name: check tag and branch
      if: steps.tag-commit-hash.outputs.tag-hash != steps.master-commit-hash.outputs.master-hash
      run: exit 1

  build-base:
    needs: [check-tag-branch]
    runs-on: ubuntu-latest
    steps:
    - name: setup python
      uses: actions/setup-python@v1
    - name: echo something
      run: echo "This steps run successfully"
 
This GitHub action is triggered when the tag is published. The job check-tag-branch check if the tag commit hash and the master branch commit hash is the same. If it’s the same then it runs another job (build-base) else if the tag is published from some other branches then the check-tag-branch job will fail. Since the build-base job needs check-tag-branch to pass, the job won’t run.

Leave a Reply

Your email address will not be published. Required fields are marked *