Conditional variable settings

Hi,

I’m creating docker image in my CI/CD. I’m currently using $CI_COMMIT_REF_SLUG but I’d like to use CI_COMMIT_TAG is it exists and only revert to $CI_COMMIT_REF_SLUG if it does not.

What’s a simple way to accomplish this? I have not seen a way to conditionally set a variable on the variable section.

Can you suggest a proper way to do this?

I’, currently doong:

build_image:
  image: docker
  tags:
    - django

  variables:
    ENV: dev
    DOCKER_BUILDKIT: 1
    IMAGE_NAME: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG

TIA

The simplest way, IMO, is to use variables and rules, like this:

variables:
    RELEASE_TAG: $CI_COMMIT_TAG
    FEATURE_BRANCH_TAG: $CI_COMMIT_REF_SLUG

.docker:
    stage: docker
    image: docker:stable
    services:
        - docker:dind
    before_script:
        -  docker login ...
    script:
        - ...

docker:featurebranch:
    extends: .docker
    variables:
        IMAGE_NAME: $FEATURE_BRANCH_TAG
    rules:
        - if: $CI_COMMIT_TAG
          when: never
        - when: always

docker:release:
    extends: .docker
    variables:
        IMAGE_NAME: $RELEASE_TAG
    rules:
        - if: $CI_COMMIT_TAG
          when: always
        - when: never

Thanks, that worked! and I leant how rules work

In the meanwhile I also realized that CI_COMMIT_REF_SLUG already has the tag instead of the branch if a tag exists… (though with a “-” where a “.” would be preferred, but that’s easy to fix)

*:wink:

1 Like