Access variables in Dockerfile

Correct me if I’m on the wrong track here, but I want to build my own Docker image during the pipelines and therefor need to clone the repository (Maybe this can be done before the Dockerfile, in gitlab-ci.yml?)

I’m trying to run something like this:

RUN git clone --progress https://$USER:$PASSWORD@gitlab.com/$REPOSITORY -b $BRANCH .

But I have failed to understand, how I can pass variables from the Gitlab runner into my Docker image?

(I can see some suggested topics on this, but none of them have any replies)

When you run a pipeline, the repo for your project is automatically downloaded. By default, your before_script, script, and after_script commands will start from the root of your repo. So, you shouldn’t need to clone from the Dockerfile, unless you need to clone a different repo, for some reason.

This blog post shows an example .gitlab-ci.yml which builds a Dockerfile.

Thanks again. Where are my files clone to or how can I change the path?

It will be a directory stored in CI_PROJECT_DIR (docs here), but your code from .gitlab-ci.yml will run from that directory, so you don’t need to cd to the directory.

I’m not sure what is wrong here, I have tried a lot of different things, but every time the files are not present in the Docker build.

This is my .gitlab-ci.yml

build:
  image: docker:stable
  services:
    - docker:dind
  stage: build
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker build -t $CI_REGISTRY/org/project/master:latest --build-arg CI_PROJECT_DIR=$CI_PROJECT_DIR .
    - docker push $CI_REGISTRY/org/project/master:latest
  only:
    refs:
      - master
    changes:
      - Dockerfile

Seems that I fixed it by adding this in my Dockerfile:

ADD . .

Right, so I think there are a couple of different questions here. Your .gitlab-ci.yml file looks OK to me, and if it’s building a Docker image then that should be fine.

If you want specific files from the repo to be added to your Docker image, then you will need to use ADD or COPY in your Dockerfile to do that. However, you should not need to clone the repo again, because the GitLab CI runner has already cloned the repo for you, before your script from your build stage has run.

Does that make more sense?