Home > Software design >  Gitlab: How to pass CI_JOB_TOKEN to Docker to be used with maven?
Gitlab: How to pass CI_JOB_TOKEN to Docker to be used with maven?

Time:12-30

I have a ci_settings.xml. With it im building artifacts and deploy them to the gitlab package repository:

<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
    <servers>
        <server>
            <id>gitlab-maven</id>
            <configuration>
                <httpHeaders>
                    <property>
                        <name>Job-Token</name>
                        <value>${env.CI_JOB_TOKEN}</value>
                    </property>
                </httpHeaders>
            </configuration>
        </server>
    </servers>
</settings>

But if I also want to be able do this in a docker container I need to pass the CI_JOB_TOKEN to the docker container. Yet I have not been able to find out how to do that.

My dockerfile:

FROM maven:3.8.1-jdk-11

COPY pom.xml /
COPY ci_settings.xml /build/
COPY lombok.config /build/
COPY app/pom.xml /build/
COPY app/src /build/src

WORKDIR /build/

ARG CI_JOB_TOKEN
ENV CI_JOB_TOKEN=$CI_JOB_TOKEN

RUN mvn package -B -s ci_settings.xml
RUN cp /build/target/*.jar /app.jar

ENTRYPOINT ["java", "-jar", "/app.jar"]

My gitlab-ci.yml:

stages:
  - build

variables:
  IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG # TODO semantic versioning

before_script:
  - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY

build:
  stage: build
#  variables:
#    CI_JOB_TOKEN: "${CI_JOB_TOKEN}" # does not work
  script:
#    - echo "CI_JOB_TOKEN=$CI_JOB_TOKEN" >> .env # does not work
    - docker info
    # setting it as build-arg also does not work
    - docker build --build-arg CI_JOB_TOKEN=${CI_JOB_TOKEN} -f app/Dockerfile --pull -t $IMAGE .
    - docker push $IMAGE

What do I need to do to pass the CI_JOB_TOKEN to the docker container so that ${env.CI_JOB_TOKEN} inside the ci_settings.xml which I copy to the container is getting resolved correctly?

CodePudding user response:

Use something like

RUN sed -i "s/CI_JOB_TOKEN/$CI_JOB_TOKEN/" ci_settings.xml

after the file is copied, and replace ${env.CI_JOB_TOKEN} by CI_JOB_TOKEN in your xml file to simplify the substitution.

  • Related