首页 > 解决方案 > 如何在声明式管道中使用 NodeLabel 参数插件

问题描述

我试图将我的自由式工作转换为声明性管道工作,因为管道提供了更大的灵活性。但是,我无法弄清楚如何在管道中使用 NodeLabel 参数插件(https://wiki.jenkins.io/display/JENKINS/NodeLabel+Parameter+Plugin)。

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')
            }
        }
    }
}

我基本上只需要一种方法来使用指定在何处构建作业的参数(使用从标签)来启动作业。

詹金斯需要一个代理字段,我将其设置为“任何”。但似乎没有可用的标签参数?

作为替代方案,我尝试使用“节点”命令(https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#-node-allocate node)。但这给我留下了两个正在运行的工作,在工作时,看起来并不那么漂亮。

是否有人可以使用 NodeLabel 参数插件?或者也许有人有更清洁的方法?

编辑:也许我不清楚。我需要能够在不同的节点上运行作业。在通过参数触发作业时应确定要运行的节点。节点标签插件完美地做到了这一点。但是,我无法在管道中重现此行为。

标签: jenkinsjenkins-pluginsjenkins-pipeline

解决方案


这是一个完整的例子:

pipeline {
    parameters {
        choice(name: 'node', choices: [nodesByLabel('label')], description: 'The node to run on') //example 1: just listing all the nodes with label
        choice(name: 'node2', choices: ['label'] + nodesByLabel('label'), description: 'The node to run on') //example 2: add the label itself as the first choice to make "Any of the nodes" the default choice
    }
    
    agent none
    stages {
        stage('Test') {
            agent { label params.node}
            stages {
                stage('Print environment settings') {
                    steps {
                        echo "running on ${env.NODE_NAME}"
                        sh 'printenv | sort'
                    }
                }
            }
        }
    }
}

推荐阅读