How can i use multiple type of agents in a single declarative jenksinfile

10/30/2020

How can i use multiple type of agents in a single declarative jenkinsfile. like i have two labels. 1st of type simple label

       agent {
              label "node_name"
            }

2nd of of kubernetes type.

           agent {
                     kubernetes {
                            cloud 'cloudName'
                            namespace 'NameSpaceName'
                            label 'AgentLabel'
                            inheritFrom 'agent'
                        }
           }

And i want to select between these two based on a condition like if some parameter is given, then run node agent , else run kubernetes agent.

-- Abhishek tomar
agent
groovy
jenkins-pipeline
kubernetes
pipeline

1 Answer

10/30/2020

I believe it is not possible exactly in the way you want, but you could work around by defining agents at the stage level:

pipeline {
	agent none

	stages {
		stage('A') {
			when { /* some condition */ }
			agent {
				label "node_name"
			}
			steps {
			    sameCodeForBothStages()
			}
		}
		stage('B') {
			when { /* some condition */ }
			agent {
				kubernetes {
					cloud 'cloudName'
					namespace 'NameSpaceName'
					label 'AgentLabel'
					inheritFrom 'agent'
				}
			}		
			steps {
			    sameCodeForBothStages()
			}
		}
	}
}

void sameCodeForBothStages() {
    sh "echo 'Hello'"
}

The obvious disadvantage is that two separate stages will show up in the pipeline view.

To avoid duplicate code on both stages you could call a function like I did in the example.

-- zett42
Source: StackOverflow