Search code examples
javadockermavenjenkinsdeployment

.m2/settings.xml in docker container not reading env variables


I am trying to deploy an artifact to a remote maven repo from inside a docker container. As part of our CI/CD pipeline, I have a jenkins job running a script that builds a docker image with maven. From inside the docker, the .jar is built and should then pushed to a remote maven repository.

here's the script:

#!/bin/bash

docker build  -t java-maven-builder .

docker run --rm -v "$PWD/target:/app/out/target" \
    -e M2_USERNAME=$M2_USERNAME \
    -e M2_PASSWORD=$M2_PASSWORD \
    java-maven-builder

Dockerfile:

FROM maven:3.9.6

USER root

WORKDIR /app

COPY . /app

COPY settings.xml /root/.m2/settings.xml

RUN chmod +x /app/build_target.sh

ENTRYPOINT ["./build_target.sh"]

and the build_target script:

#!/bin/bash
echo "M2_USERNAME: $M2_USERNAME"
echo "M2_PASSWORD: $M2_PASSWORD"

mvn -X clean package verify deploy

cp -r /app/target/* /app/out/target

finally, here's the settings.xml file

<settings>
<servers>
    <server>
        <id>snapshots</id>
        <username>${env.M2_USERNAME}</username>
        <password>${env.M2_PASSWORD}</password>
    </server>
</servers>
</settings>

the M2_USERNAME and M2_PASSWORD are read from a secrets file in jenkins and passed as environment variable to the docker at runtime. They seem to be correctly passed to docker, as the echo commands in the build_target.sh script correctly print out the values. However, I get a 401-Unauthorized when maven tries to deploy to the remote repo, as if the crentials where wrong.

NB: I did try to hardcode the values in the settings.xml and in that case everything works, I just don't seem to be able to pass them as env variables.

Any ideas?


Solution

  • Turns out the problem was not in the environment variables after all...

    I was able to check weather the settings.xml file was reading the env variables correctly by running:

    mvn help:effective-settings
    

    and noticed that they were being correctly parsed.

    The actual problem was that, in my settings file, I only had the credentials set up for the snapshots directory and not for the central one.

    Since I had changed the version name in the pom.xml to something that did not include -SNAPSHOT, maven was trying to deploy it on the central repo and was not able to find the credentials.

    The issue was solved by adding:

    <server>
       <id>central</id>
       <username>${env.M2_USERNAME}</username>
       <password>${env.M2_PASSWORD}</password>
    </server>
    

    to the settings.xml file

    In the end there was nothing wrong with either docker nor maven. It was just my poor understanding of the maven build lifecycle :)