Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

gitlab-ci check if branch is a tag or not and then executes commands based on branch type

I would like to check if a branch is a tag or not in a single stage in gitlab-ci.yml. Then based on whether a branch is a tag or not, a specific set of commands are executed:

IF tag:
   A SET OF COMMANDS
ELSE:
   ANOTHER SET OF COMMAND

I am aware that only: -tags can be used to check if a branch is a tag, but how can I check the branch and then apply different sets of commands based on the branch type in a single gitlab-ci stage? In this case, if a branch is not a tag, I would to apply a different set of commands.

some_stage:
  only:
    - tags
  script:
    - | SET OF COMMANDS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Gitlab-CI predefined variables:

  • CI_COMMIT_BRANCH (The commit branch name. Available in branch pipelines, including pipelines for the default branch. Not available in merge request pipelines or tag pipelines.)
  • CI_COMMIT_TAG (The commit tag name. Available only in pipelines for tags.)

The "CI_COMMIT_BRANCH" variable will hold the branch name only if pipeline is triggered from branch, otherwise it will not hold any value.
The same applies on the "CI_COMMIT_TAG" variable that will hold values only in case of pipeline triggered from tag.

You can use rules to check these variables and decide if you want to execute a job or not.
for example, if you want to build docker images from tags only:

build_docker:
  rules:
    - if: '$CI_COMMIT_TAG != null && $CI_BUILD_TAG =~ *SOME_REGEX*'
      when: on_success

Update: Or you can use variable inside script to do you check but i recommend that you split the logic into to jobs. one for tags work and another for branch job. and specify with rules when a job is executed.

last thing: there is a deprecated tag called CI_BUILD_TAG, so if you are using an old version of gitlab.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading