Harpreet
Harpreet

Reputation: 1607

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

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

Upvotes: 6

Views: 5033

Answers (4)

zulucoda
zulucoda

Reputation: 868

Adding a much better answer to this question.

Step 1: Define Variables

In your .gitlab-ci.yml or in your GitLab project's CI/CD settings, define the variables you need.

.gitlab-ci.yml Example:

variables:
  MY_VARIABLE: "my_value"

Step 2: Use Variables in Docker Compose

In your docker-compose.yml, utilize environment variables.

docker-compose.yml Example:

version: '3.8'

services:
  myservice:
   image: myimage:latest
   environment:
     MY_ENV_VARIABLE: "${MY_VARIABLE}"

Upvotes: 0

Harpreet
Harpreet

Reputation: 1607

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

Upvotes: 4

Partiban
Partiban

Reputation: 166

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?

Upvotes: 0

Yasen
Yasen

Reputation: 4504

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}

Upvotes: 0

Related Questions