使用jenkins pipeline基于参数值选择代理标签

问题描述 投票:0回答:4

我有这个示例管道(其中一部分):

pipeline {
    parameters {
        choice(name: 'myParam', choices: ['1','2'], description: 'param desc')
    }
    options { timestamps () }
    agent {
        node {
            label 'myLabel'
        }
    }

我的问题是这样的:

我想根据用户对 myParam 的选择更改我的代理标签的 myLabel。 在这种情况下,我希望当 myParam 为 1 时,myLabel 将等于“linux_first”,而当 myParam 为 2 时,myLabel 将等于“linux_second”。

有谁知道有什么办法吗? 提前致谢, 阿隆

jenkins jenkins-pipeline jenkins-plugins
4个回答
1
投票

我有一个非常相似的需求,我通过将参数设置为标签本身来解决它:

pipeline {
    parameters {
        choice(
            name: 'myParam',
            choices: ['linux_first','linux_second'],
            description: 'param desc'
        )
    }
    options { timestamps() }
    agent { label "${params.myParam}" }
    stages {
        stage('Greeting') {
            steps {
                echo "Hello from ${env.NODE_NAME}"
            }
        }
    }
}

如果你想保留你的

choices: ['1','2']
,那么它会更复杂,并且涉及一个单独阶段中的一段脚本化管道:

pipeline {
    agent none
    parameters {
        choice(name: 'myParam', choices: ['1','2'], description: 'param desc')
    }
    options { timestamps() }
    stages {
        stage('Configure') {
            steps {
                script {
                    if (params.myParam == '1') {
                        MY_AGENT_LABEL = 'linux_first'
                    } else {
                        MY_AGENT_LABEL = 'linux_second'
                    }
                }
            }
        }
        stage('Greeting') {
            agent { label "${MY_AGENT_LABEL}" }
            steps {
                echo "Hello from ${env.NODE_NAME}"
            }
        }
    }
}

0
投票

方法1-

您可以尝试“nodeLabelParameter”插件。根据您的要求,它可能会帮助您。

https://plugins.jenkins.io/nodelabelparameter/

该插件在作业配置中添加了两种新的参数类型 - 节点和标签。新参数允许动态选择应执行作业的节点或标签。

方法2-

基本语法是定义管道参数并使用它。

agent {
label "${build_agent}"
}

0
投票

您可以在声明性管道中以这种方式参数化代理

properties([
   string(description: 'build Agent', name: 'build_agent')
])

pipeline {
   agent {
      label params['build_agent']
   }
   stages {
      // steps 
   }
}

0
投票

我刚刚遇到了类似的需求,我想在这里提供一个稍微更灵活的选项。您可以在标签中使用原始参数值的字符串插值,但也可以使用内联条件或函数调用,以便您可以拥有尽可能多的控制权。

带条件的示例:

pipeline {
    agent {
        node {
            label 'label' + (params.myParam == 'option one' ? '_1' : '_2')
        }
    }
...

带函数调用的示例:

String get_agent_label(String input_param) {
    if (input_param == 'option one') {
        return 'label_1'
    } else if (input_param == 'option two') {
        return 'label_2'
    }
    return 'label_default'
}

pipeline {
    agent {
        node {
            label get_agent_label(params.myParam)
        }
    }
...
© www.soinside.com 2019 - 2024. All rights reserved.