I have a GitLab CI/CD configuration where I want the pipeline to be triggered only when changes are pushed to the master branch. Below is a simplified version of my .gitlab-ci.yml
file:
stages:
- deploy
deploy:
stage: deploy
rules:
- if: '$CI_COMMIT_REF_NAME == "master"'
- when: manual
before_script:
- apt-get update && apt-get install sshpass && apt-get install make
- chmod 400 $SSH_KEY
script:
- sshpass -p $SSH_PASS ssh -o "StrictHostKeyChecking=no" $USER_NAME@$HOST "cd /home/backend && git pull && make docker-restart"
With this configuration, the pipeline should only run when changes are pushed to the master branch. However, it seems like the pipeline is triggered even when changes are pushed to other branches.
How can I modify my GitLab CI/CD configuration to ensure that the pipeline is triggered only when changes are pushed to the master branch?
There's a small typo in your if
key, but besides that I think you'd be better using the variable $CI_COMMIT_BRANCH
instead, as the one you're currently using takes into account tags too. Also as a small improvement, if your default branch is master
you can do the check with a variable too:
stages:
- deploy
deploy:
stage: deploy
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
before_script:
- apt-get update && apt-get install sshpass && apt-get install make
- chmod 400 $SSH_KEY
script:
- sshpass -p $SSH_PASS ssh -o "StrictHostKeyChecking=no" $USER_NAME@$HOST "cd /home/backend && git pull && make docker-restart"
Full reference for GitLab's predefined variables can be found here.