16

I want to know, if it's possible to set custom Gitlab CI variable from if-else condition statement.

In my .gitlab-ci.yml file I have the following:

variables:
    PROJECT_VERSION: (if [ "${CI_COMMIT_TAG}" == "" ]; then "${CI_COMMIT_REF_NAME}-${CI_PIPELINE_ID}"; else ${CI_COMMIT_TAG}; fi);

Trying to set project version:
    image: php:7.1-cli
    stage: test
    script:
        # this echoes correct string (eg. "master-2794")
        - (if [ "${CI_COMMIT_TAG}" == "" ]; then echo "${CI_COMMIT_REF_NAME}-${CI_PIPELINE_ID}"; else echo ${CI_COMMIT_TAG}; fi);
        # this echoes something like "(if [ "" == "" ]; then "master-2794"; else ; fi);"
        - echo $PROJECT_VERSION

Can this be done? If so, what have I missed? Thanks

2 Answers 2

12

This is expected behavior.

CI_COMMIT_TAG is only set to a value in a GitLab job. From https://docs.gitlab.com/ee/ci/variables/README.html

CI_COMMIT_TAG - The commit tag name. Present only when building tags.

Therefore in the variables section CI_COMMIT_TAG is not defined, hence equals to "".

So if you want to use CI_COMMIT_TAG use in job where tags are defined. See https://docs.gitlab.com/ee/ci/yaml/README.html#tags

1
10

It is possible:

Add your logic into the variable section:

variables:
  VERSION_LOGIC: '(if [ "$${CI_COMMIT_TAG}" == "" ]; then echo "1.3.5.$$CI_PIPELINE_IID"; else echo "$${CI_COMMIT_TAG}"; fi);'

Now you are able to use this logic in a script secion of a job:

version:
  stage: versioning
  script:
    - VERSION=$(eval $VERSION_LOGIC)
    - echo "The current version is set to ${VERSION}."
1
  • 1
    +1 for the creative solution. not sure if I would implement it this way, it seems much simpler to just script the logic under the script lines directly. Commented Feb 17, 2020 at 14:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.