2

I have a gitlab pipeline which looks like this:

stages:
  - build
  - deploy

build:
  stage: build
  script: //do stuff

deploy:
  stage: deploy
  script: //do stuff
  only:
    - /^v\d+\.\d+\.\d+
  when: on_success

I want it to run build job for every commit, and run the deploy step if it has a tag matching the regex. It almost works, but it runs twice when I push it with tag, once with deploy step and once without it. How can I prevent that?

Krzysztof Wrona
  • 311
  • 5
  • 12
  • did you try `/^v\d+\.\d+\.\d+/`? – teedak8s Jan 03 '23 at 02:52
  • The actual regex is actually a bit more complex and it does end with /, I simplified it for the sake of example. The issue seems to be that it triggers once because commit has been pushed to develop branch, and once more because a tag has been pushed – Krzysztof Wrona Jan 04 '23 at 15:33

1 Answers1

1

Unfortunately this is the expected behavior - tags trigger a separate pipeline, even when they are part of the same push as the commit. You can block this with workflows, but in your case it would prevent the deploy job from running.

You can prevent the same job running in both pipelines with rules, which is now recommended over only/except. It's very flexible when combined with CI/CD vars. I would try the bash regex operator with CI_COMMIT_TAG:

stages:
  - build
  - deploy

build:
  stage: build
  script: //do stuff
  rules:
    - if: '$CI_COMMIT_TAG =~ "<your_regex>"'
      when: never
    - when: always

deploy:
  stage: deploy
  script: //do stuff
  rules:
    - if: '$CI_COMMIT_TAG =~ "<your_regex>"'
      when: always
    - when: never

Rules are read top to bottom until a match is found. The catch-all rules at the end ensure that:

  • build always runs unless the regex matches
  • deploy only runs when the regex matches

This will still create 2 pipelines, but it should prevent the build job from running twice and wasting minutes.

jamedeus
  • 61
  • 4