Home > OS >  CI job rule to only execute over main when the tag is present
CI job rule to only execute over main when the tag is present

Time:11-12

I have following job rule:

  rules:
    - if: '$CI_COMMIT_REF_NAME == "main" && $CI_COMMIT_TAG =~ /^v[0-9](?:\.[0-9]){2,3}/'
      when: on_success

What I want is to only execute this job when a change to main to push (direct or through MR) and has a tag matching the pattern.

But I have tried all the ways but this job never executes. This is my flow of commit

git tag -a v0.0.2 -m "Adding version"
git push origin dev # and merge to main, or directly
git push origin main

my understanding is above is a commit over main with the specified tag and should trigger this job but it isn't.

Any idea what am I doing wrong?

CodePudding user response:

In short: It's not possible. You cannot mate these two conditions at push time because, as stated in the comments, tags have no relation to branches. This is a concept rooted in git and not something GitLab has control over.

When you push a tag, there is no reference to any branch. It points to a commit. That commit may exist on one branch, many branches, or even no branch at all. When you tag a commit and push the tag, it doesn't matter what your current working branch is. There's no branch information associated with that push of the tag.

That's part of the reason why branch pipelines are separate from tag pipelines and why the CI_COMMIT_BRANCH variable is not present for tag pipelines and CI_COMMIT_TAG is not present on branch pipelines. That's also why the CI_COMMIT_REF_NAME variable is EITHER the branch name OR the tag.

Therefore, if you're expecting CI_COMMIT_TAG to be present, CI_COMMIT_REF_NAME and CI_COMMIT_TAG will always be the same. Hence, your rule can never evaluate as true as your rule relies on them being different, which, inherently, can never happen based on the properties discussed above.

Illustrated in a table:

Variable Branch pipelines Tag Pipelines
CI_COMMIT_REF_NAME my-branch tag-name
CI_COMMIT_BRANCH my-branch
CI_COMMIT_TAG tag-name

What you're asking for is simply not possible using rules:.

You might be able to achieve something like what you want by introspecting the HEAD on a branch pipeline job for main using git to see if a tag matching the pattern exists and then using dynamic child pipelines to trigger the desired workflow thereafter.

But that approach is error-prone for a number of reasons and the better route is almost certainly to rethink your workflow.

  • Related