Template docker agent in jenkins Declarative pipeline
Asked Answered
B

0

8

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

Billetdoux answered 13/12, 2017 at 12:1 Comment(1)
Based on my unfruitful searches for this exact question, it does not appear that there is a solution.Tyrrell

© 2022 - 2024 — McMap. All rights reserved.