0

In job rules you cannot do:

test_prod:
  stage: deploy
  environment: 
     name: $ENVIRONMENT
  script:
    - echo $ENVIRONMENT
    - echo $CI_COMMIT_TAG
  rules:
   - if: $CI_COMMIT_BRANCH == "main" && $CI_COMMIT_TAG

According to this post: $CI_COMMIT_TAG in "if" statemets of regular job

"For example, if you simply push a new commit to the remote, the value of CI_PIPELINE_SOURCE will be push. For push pipelines, many of the Predefined Variables will not exist, such as CI_COMMIT_TAG, CI_MERGE_REQUEST_SOURCE_BRANCH_NAME, CI_EXTERNAL_PULL_REQUEST_SOURCE_BRANCH_NAME, etc.

However if you create a Git Tag either in the GitLab UI or from a git push --tags command, it will create a Tag pipeline, and variables like CI_COMMIT_TAG will exist, but CI_COMMIT_BRANCH will not."

What is the reason for that?

eco
  • 1,254
  • 1
  • 12
  • 22

1 Answers1

0

This is because git operates with tree structures and therefore pointers. Please refer to this gitlab issue for more details with comments by Drew Stachon: https://gitlab.com/gitlab-org/gitlab/-/issues/34578#note_381469101

Unfortunately, this concept of "a tag on a branch" doesn't really exist in Git. v0.0.2 and master are just two different refs, and one of them happens to point to a SHA in the revision history of another ref. To say that v0.0.2 is on master is like saying that master is on your up-to-date feature branch. You could conceivably build this logic into a CI job, but it would involve detecting a tag ref and comparing the SHA to every SHA in the revision history of master and either continuing the job or exit 0-ing, or whatever. But I strongly recommend not doing this. I'm guessing that the tag v0.0.2 has a particular significance here by being in the revision history of master. If that's the case (e.g. you're using tags to release versions), then I recommend adopting a specific naming convention for tags that are created on master, and not using them elsewhere. The CI rule would kick off some particular job on $CI_COMMIT_TAG =~ /^v\d+.\d+.\d+$/, and it's a business rule that those tags only get created on commits in master. We use this workflow on a smaller project and it works well for us. You should also have tags set to protected in your repository if you're using them to release things. Let me know if that's helpful, or if there's anything I can clarify.

eco
  • 1,254
  • 1
  • 12
  • 22