Template docker agent in jenkins Declarative pipeline

[亡魂溺海] 提交于 2019-12-07 18:04:49

问题


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

来源:https://stackoverflow.com/questions/47792511/template-docker-agent-in-jenkins-declarative-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!