amacrobert
amacrobert

Reputation: 3179

Add the repo root as a Docker volume in a Jenkins declarative pipeline

I am running a CI pipeline for a repo in Jenkins using declarative pipeline.

The repo now contains its own Dockerfile at .docker/php/Dockerfile, which I want to use to build a container and run the pipeline in.

Normally, I get the code in the container using a volume in docker-compose.yaml:

    volumes:
        - .:/home/wwwroot/comms-and-push

...So I set up my Jenkinsfile like this:

pipeline {

    agent {
        dockerfile {
            dir ".docker/php"
            args "-v .:/home/wwwroot/comms-and-push"
        }
    }

    stages {

    ...

However, this results in an error when running the pipeline:

Error: docker: Error response from daemon: create .: volume name is too short, names should be at least two alphanumeric characters.

I cannot specify the full path because I don't know it in this context -- it's running in some Jenkins workspace.


What I've tried so far:

Using the WORKSPACE variable

        args "-v ${WORKSPACE}:/home/wwwroot/comms-and-push"

results in error:

No such property: WORKSPACE for class: groovy.lang.Binding

Setting an environment variable before the pipeline:

environment {
    def WORKSPACE = pwd()
}

pipeline {

    agent {
        dockerfile {
            dir '.docker/php'
            args "-v ${env.WORKSPACE}/:/home/wwwroot/comms-and-push"
        }
    }
    ...

results in ${env.WORKSPACE} resolving to null.

Upvotes: 1

Views: 907

Answers (2)

Foxy Fox
Foxy Fox

Reputation: 501

I would suggest to use the docker.image.inside() method, so in your case it is going to be something like docker.image.inside("-v /home/wwwroot/comms-and-push:/home/wwwroot/comms-and-push:rw").

Upvotes: 0

David Maze
David Maze

Reputation: 160003

The standard Jenkins Docker integration already knows how to mount the workspace directory into a container. It has the same filesystem path inside different containers and directly on a worker outside a container. You don't need to supply a docker run -v argument yourself.

agent {
    dockerfile {
        dir ".docker/php"
        // No args
    }
}

stages {
    stage('Diagnostics') {
        sh "pwd"  // Prints the WORKSPACE
        sh "ls"   // Shows the build tree contents
        sh "ls /" // Shows the image's root directory
    }
}

If you look at the extended Jenkins logs, you'll see that it provides the -v option itself.

Upvotes: 1

Related Questions