Home > Back-end >  Check that gitlab branch has changes before running jobs
Check that gitlab branch has changes before running jobs

Time:02-03

In order to stop the current default Gitlab behaviour of starting pipelines on branch creation I am trying to add a check in each job so that only merge requests trigger jobs when they have changes.

This is what I got so far:

  rules:
    - if: '[$CI_PIPELINE_SOURCE == "merge_request_event"] && [! git diff-index --quiet HEAD --]'

I am not quite familiar with bash which is surely the problem because I am currently encountering a 'yaml invalid' error :d

PS: Is there maybe a better way to do this instead of adding the check to each task?

CodePudding user response:

i don't know if it can be useful, but Gitlab-ci provide the only job keyword that you can combine with changes and insert a path to files, in this way you can execute jobs only if there are changes on the code you are interested on.

Example

docker build:
  script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
  only:
    refs:
      - branches
    changes:
      - Dockerfile
      - docker/scripts/*
      - dockerfiles/**/*
      - more_scripts/*.{rb,py,sh}
      - "**/*.json"

DOC: https://docs.gitlab.com/ee/ci/yaml/#onlychanges--exceptchanges

CodePudding user response:

I am not quite familiar with bash which is surely the problem because I am currently encountering a 'yaml invalid' error :d

The issue seems to be with

[! git diff-index --quiet HEAD --]

You can not use bash syntax in Gitlab rules but to script section you can, as the name implies

In order to stop the current default Gitlab behaviour of starting pipelines on branch creation

If this is your goal I would recommend the following rules

workflow:
  rules:
    - if: $CI_COMMIT_BEFORE_SHA == "0000000000000000000000000000000000000000"
      when: never
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_PIPELINE_SOURCE == "push"

Let's break down the aforementioned rules

The following rule will stop the execution of a new pipeline when a new branch is created

- if: $CI_COMMIT_BEFORE_SHA == "0000000000000000000000000000000000000000"
  when: never

The following rule will be true for merge requests

if: $CI_PIPELINE_SOURCE == "merge_request_event"

The following rule will be true for a new pushed commit

- if: $CI_PIPELINE_SOURCE == "push"

PS: Is there maybe a better way to do this instead of adding the check to each task?

The aforementioned rules dont have to be added for each job, but instead are configured once for each pipeline take a look https://docs.gitlab.com/ee/ci/yaml/workflow.html

Basicaly, add the workflow rules statement at the start of your gitlab.yml and you are good to go

  •  Tags:  
  • Related