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

Time:07-08

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

CodePudding user response:

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.

  • Related