Template docker agent in jenkins Declarative pipel

2019-05-13 19:38发布

问题:

I have a Jenkinsfile for a declarative pipeline that uses docker agents. A number of the steps use a docker agent and it is a bit repetitive adding the same agent for these steps

e.g.

pipeline {
  agent any
  stages {  
    stage('Stage 1') {
      steps {
        //Do something
      }
    }
    stage('Stage 2') {      
      agent {
        docker { image 'jenkins/jenkins-slave:latest'
                 reuseNode true
                 registryUrl 'https://some.registry/'
                 registryCredentialsId 'git'
           args '-v /etc/passwd:/etc/passwd -v /etc/group:/etc/group -e HOME=${WORKSPACE}' 
        }                         
      }
      steps {
         //Do something
      }
    }
    stage('Stage 3') {
      steps {
        //Do something
      }
    }
    stage('Stage 4') {      
      agent {
        docker { image 'jenkins/jenkins-slave:latest'
                 reuseNode true
                 registryUrl 'https://some.registry/'
                 registryCredentialsId 'git'
           args '-v /etc/passwd:/etc/passwd -v /etc/group:/etc/group -e HOME=${WORKSPACE}' 
        }                         
      }
      steps {
         //Do something
      }
    }
  }
}

Is there any way to template the agent (or write my own) so that I could do something like the following

pipeline {
  agent any
  stages {  
    stage('Stage 1') {
      steps {
        //Do something
      }
    }
    stage('Stage 2') {      
      agent {
        my-docker                     
      }
      steps {
         //Do something
      }
    }
    stage('Stage 3') {
      steps {
        //Do something
      }
    }
    stage('Stage 4') {      
      agent {
        my-docker             
      }
      steps {
         //Do something
      }
    }
  }
}

So that I do not have to repeatly write the same agent and possibly I can reuse it in all my Dockerfiles