Using gitlab-ci default variables in docker-compose.yaml

Viewed 3267

I want to tag the docker image with default git variable for branch name CI_COMMIT_BRANCH

But when I run the code the value of CI_COMMIT_BRANCH becomes an empty string and hence the docker image is tagged as _service1 without branch name.

.gitlab-ci.yml

Tag Images:
  stage: push images
  script:
    - sudo docker-compose build

docker-compose.yaml

version: '2.1'
services:
  service1:
    build: ./service1
    image: service1:${CI_COMMIT_BRANCH}_service1
3 Answers

Solved this by adding the variable to .env file dynamically

.gitlab-ci.yml

Tag Images:
  stage: push images
  before_script:
    - echo 'BRANCH_NAME='$CI_COMMIT_BRANCH >> .env #This command will create .env if not exists 
  script:
    - sudo docker-compose build

docker-compose.yaml

version: '2.1'
services:
  service1:
    build: ./service1
    image: service1:${BRANCH_NAME}_service1

Pass variables to docker-compose

You may:

  • either pass variable with -e

See manual Set environment variables

  • or create env file containing declared variables and pass it's name with --env-file

See manual

Export variables in .gitlab-ci.yml

Also, you cat try to export variable in before_script block of `gitlab-ci.yml':

before_script:
  - export IMAGE_NAME=service1:${CI_COMMIT_BRANCH}_service1

docker-compose.yml:

version: '2.1'
services:
  service1:
    build: ./service1
    image: ${IMAGE_NAME}

Looking at the predefined_variables, I don't think CI_COMMIT_BRANCH is the correct variable to use in your scenario, as the commit branch name is "Present only when building branches." (Which i'm guessing is the cause of the _service1 docker image tag)

Perhaps, you could use CI_COMMIT_REF_NAME instead?

Related