Search code examples
jenkinsjenkins-pluginsjenkins-pipeline

How to use NodeLabel parameter plugin in declarative pipeline


Im trying to convert my freestyle job to a declarative pipeline job since the pipeline provides more flexibility. I cannot figure out how to use the NodeLabel parameter plugin (https://wiki.jenkins.io/display/JENKINS/NodeLabel+Parameter+Plugin) in a pipeline however.

pipeline {
agent any

parameters {
    // Would like something like LabelParameter here
}

stages {
    stage('Dummy1') {
        steps {
            cleanWs()
            sh('ls')
            sh('pwd')
            sh('hostname')
        }
    }
    stage('Dummy2') {
        steps {
            node("comms-test02") {
                sh('ls')
                sh('pwd')
                sh('hostname')
            }
        }
    }
}

I basically just need a way to start the job using a parameter that specifies where to build the job (using slave label).

Jenkins requires an agent field to be present which i set to 'any'. But it doesnt seem like there is a labelparameter available ?

As an alternative I tried using the 'node' command (https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#-node- allocate node). But that leaves me with two running jobs which, while working, doesnt look that pretty.

Does anyone if the NodeLabel parameter plugin can be used ? or maybe someone has a cleaner approach ?

Edit: Maybe I wasn't clear. I need to be able to run jobs on different nodes. The node to run on should be decided when triggering the job through a parameter. The node label plugin does this perfectly. However, I have not been able to reproduce this behavior in pipeline.


Solution

  • Let's say you added the parameter(say named slaveName) using the NodeLabel plugin on your pipeline. You now need to extract the value of slaveName and feed it into the agent->node->label field.

    You can specify the node using the node property inside the agent. Like this -

    agent
    {
        node
        {
            label "${slaveName}"
        }
    }