Arvid Terzibaschian
Arvid Terzibaschian

Reputation: 327

how to run jenkins declarative pipeline on node selected via parameter and label option

I want to run a pipeline with the node set as parameter via the Node and Label plugin. run with parameters screenshot

How do I change the declarative pipeline

pipeline {
    agent  {
        label 'whatever'
    }
...

to use EXECUTION_NODE as agent to execute the pipeline? This seems to be much more complicated than I thought, or I am missing something obvious.

Upvotes: 2

Views: 3781

Answers (1)

MaratC
MaratC

Reputation: 6869

The issue is this: to present you the "Build with parameters" page, Jenkins needs to run your pipeline and parse its parameters. To run a pipeline, Jenkins needs a node. To have a node, it parses your pipeline. So the node is already selected by the time the dialog is shown. Moreover, in declarative pipeline all the nodes of all the stages get selected in the beginning.

You can try running a scripted pipeline or a combination of scripted and declarative, by running node and supplying params.EXECUTION_NODE as label. Scripted pipeline executes the script line by line.

Edit: this is working:

NODE = null
echo "This should be Null: $NODE"

node() {
    stage("Define node") {
        NODE = params.NODE
        echo "This is now $NODE"
    }
}
    
pipeline {
    agent { node { label "$NODE" }}
    parameters { string(name: 'NODE', defaultValue: 'some_node', description: '') }
    stages {
        stage("Main") {
            steps {
                echo "Hi"
            }
        }
    }
}

Here is an output of a second run with 'master' as parameter:

Started by user marat 
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] echo
This should be Null: null
[Pipeline] node
Running on Jenkins in /home/jenkins/workspace/test
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Define node)
[Pipeline] echo
This is now master
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] node
Running on master in /var/jenkins_home/workspace/test
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Main)
[Pipeline] echo
Hi
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Upvotes: 1

Related Questions