1

Our current Jenkins pipeline looks like this:

pipeline {

  agent {
    docker {
      label 'linux'
      image 'java:8'
      args '-v /home/tester/.gradle:/.gradle'
    }
  }

  environment {
    GRADLE_USER_HOME = '/.gradle'
    GRADLE_PROPERTIES = credentials('gradle.properties')
  }

  stages {
    stage('Build') {
      steps {
        sh 'cp ${GRADLE_PROPERTIES} ${GRADLE_USER_HOME}/'
        sh './gradlew clean check'
      }
    }
  }

  post {
    always {
      junit 'build/test-results/**/*.xml'
    }
  }

}

We mount /.gradle because we want to reuse cached data between builds. The problem is, if the machine is a brand new build machine, the directory on the host does not yet exist.

Where do I put setup logic which runs before, so that I can ensure this directory exists before the docker image is run?

Hakanai
  • 12,010
  • 10
  • 62
  • 132

1 Answers1

2

You can run a prepare stage before all the stages and change agent after that

pipeline {

  agent { label 'linux' } // slave where docker agent needs to run

  environment {
    GRADLE_USER_HOME = '/.gradle'
    GRADLE_PROPERTIES = credentials('gradle.properties')
  }

  stages {

    stage('Prepare') {
      // prepare host
    }

    stage('Build') {

      agent {
        docker {
          label 'linux' // should be same as slave label
          image 'java:8'
          args '-v /home/tester/.gradle:/.gradle'
        }
      }

      steps {
        sh 'cp ${GRADLE_PROPERTIES} ${GRADLE_USER_HOME}/'
        sh './gradlew clean check'
      }
    }
  }

  post {
    always {
      junit 'build/test-results/**/*.xml'
    }
  }

}

Specifying a Docker Label

Pipeline provides a global option in the Manage Jenkins page, and on the Folder level, for specifying which agents (by Label) to use for running Docker-based Pipelines.

How to restrict the jenkins pipeline docker agent in specific slave?

Yogesh
  • 4,546
  • 2
  • 32
  • 41
  • 1
    How can I be sure that the `agent{docker{label 'linux'}}` will get the same agent that the prepare stage got? – Hakanai Nov 01 '18 at 23:22
  • updated for restricting docker agent on certain host – Yogesh Nov 02 '18 at 10:25
  • So is there a hidden detail here? Both times it only specifies a label, but is there a guarantee that you'll get the same host even if there are 18 hosts with the same label? – Hakanai Nov 03 '18 at 22:54
  • You can't have duplicate node names (Jenkins Slaves) which is used as hosts for docker – Yogesh Nov 05 '18 at 07:45
  • We don't actually have duplicate node names. 'linux' is a label we apply to 18 hosts which all run various distros of Linux. We certainly can't reduce ourselves to running on a single host anyway, we barely have enough processing power to build everything as it is. :( – Hakanai Nov 06 '18 at 00:11