22

I have several jenkins slaves configured and only label with dockerserver has docker env, then how can I restrict the jenkins pipeline docker agent in this slave?

Below Jenkinsfile doesn't work, the agent inside stage will overwrite the defined slave dockerserver

pipeline {
    agent { label 'dockerserver' }
    stages {
        stage('Back-end') {
            agent {
                docker { image 'maven:3-alpine' }
            }
            steps {
                sh 'mvn --version'
            }
        }
        stage('Front-end') {
            agent {
                docker { image 'node:7-alpine' }
            }
            steps {
                sh 'node --version'
            }
        }
    }
}

It may pick other slave which doesn't have docker supported

Any suggestion?

Larry Cai
  • 55,923
  • 34
  • 110
  • 156

2 Answers2

18

Just had the same problem, seems to work for me like this:

pipeline {
    agent { label 'dockerserver' } // if you don't have other steps, 'any' agent works
    stages {
        stage('Back-end') {
            agent {
                docker {
                  label 'dockerserver'  // both label and image
                  image 'maven:3-alpine'
                }
            }
            steps {
                sh 'mvn --version'
            }
        }
        stage('Front-end') {
            agent {
              docker {
                label 'dockerserver'  // both label and image
                image 'node:7-alpine' 
              }
            }
            steps {
                sh 'node --version'
            }
        }
    }
}
Quartz
  • 1,731
  • 1
  • 14
  • 17
  • 1
    This solution won't work if you want to specify `dockerfile true` as `dockerfile` is not valid within the `docker` closure. If you are using a dockerfile @Larry Cai's solution worked for me – Jon Hunter Aug 13 '20 at 07:36
13

After read the guideline more, noticed it was stated https://jenkins.io/doc/book/pipeline/docker/#specifying-a-docker-label.

enter image description here

It shall be configured in the jenkins global(system) configuration

Larry Cai
  • 55,923
  • 34
  • 110
  • 156