How to pass variables from .gitlab.ci.yml to Dockerfile

Viewed 5186

How can I pass one variables value from .gitlab-ci.yml to Dockerfile?

e.g. The .gitlab-ci.yml contains:

variables:
  var1: ex_variable_1
  var2: ex_variable_1

stages:
  - build

build:
  stage: build
  script:
    - sudo docker build . -t ${CI_PROJECT_PATH_SLUG}
                          --build-arg var1
                          --build-arg var2
    - sudo docker run -dit --name ${CI_PROJECT_PATH_SLUG} --cap-add=NET_ADMIN ${CI_PROJECT_PATH_SLUG}:latest

The Dockefile contains:

FROM centos:6.9

ENV var1 ${var1}
ENV var2 ${var2}

RUN echo "Print var1 $var1"
RUN echo "Print var2 $var2

So what I want is to pass var1 and var2 from .gitlab-ci.yml to Dockerfile.

1 Answers

To pass environment variables from .gitlab-ci.yml to an image or container:

  • at build time (if the variable is used by the Dockerfile):

    • use the docker build --build-arg option: docker build --build-arg var1="$var1"

    • and change your Dockerfile like this:

        FROM centos:6.9
        ARG var1
        ARG var2
      
        RUN echo "Print var1 $var1"
        RUN echo "Print var2 $var2
      
        # The following is optional − only useful if you want to
        # keep the environment variables at runtime (docker run)
        ENV var1=${var1}
        ENV var2=${var2}
      

      Note: the ARG instruction can also take a default value:

        ARG var1="default value if var1 was not passed using --build-arg"
      
  • at runtime (if the variable is used by the container, i.e., by the ENTRYPOINT / CMD-specified program):

Related