gitlab trigger pipeline for specific branches only

Viewed 8075

I have configured gitlab ci/cd pipeline for my project. So I have used base template which has 2 stages, build & package. Build stage builds project and create jar file and package stage create image and store it in container registry. And .gitlab-ci.yml file has been created. Below is file

image: docker:latest
services:
  - docker:dind

stages:
  - build
  - package

build:
  image: gradle:5.6.1-jdk11
  stage: build
  script:
    - gradle clean build -x test
  artifacts:
    paths:
      - build/libs/*.jar

package:
  stage: package
  script:
    - docker build -t registry.gitlab.com/my-project/sample .
    - docker login -u $CI_DOCKER_USERNAME -p $CI_DOCKER_PASSWORD registry.gitlab.com
    - docker push rregistry.gitlab.com/my-project/sample

When we want to add new functionality we obviously create new branch and since this file exist in the new branch too, build is getting triggered. But I dont want to trigger a build for all the branches. I want to trigger only development and master. Is there anyway we can do that at project level instead of adding only in each stage

2 Answers

The only way to limit when jobs are created is by using only/exceptin the .gitlab-ci.yml file.

To not have to write so much text, you can use extends and also sometimes yaml anchors. More info here:

https://docs.gitlab.com/ee/ci/yaml/#extends

and here:

https://docs.gitlab.com/ee/ci/yaml/#anchors

An example of how extends can be used:

image: docker:latest
services:
  - docker:dind

.only-master-and-develop:
  only:
   - master
   - development

stages:
  - build
  - package

build:
  extends: .only-master-and-develop
  image: gradle:5.6.1-jdk11
  stage: build
  script:
    - gradle clean build -x test
  artifacts:
    paths:
      - build/libs/*.jar

package:
  extends: .only-master-and-develop
  stage: package
  script:
    - docker build -t registry.gitlab.com/my-project/sample .
    - docker login -u $CI_DOCKER_USERNAME -p $CI_DOCKER_PASSWORD registry.gitlab.com
    - docker push rregistry.gitlab.com/my-project/sample

(I haven't tested this file, please let me know if there's something wrong with it.)

You should specify the target branch using via $CI_COMMIT_BRANCH == "<your_branch_name>".

rules:
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "master"'
      something regarding the project..

    - if: '$CI_PIPELINE_SOURCE == "web" && $CI_COMMIT_BRANCH == "development"'
      something regarding the project..

I hope above example can help anyone!

Also here is the documentation for these types of questions.

Related