本示例展示如何使用 Jenkinsfile 脚本,通过参数选择不同的字典,并将字典中的键值对设置为全局变量,供 pipeline 中的其他阶段使用。

def dict1 = [key1: 'value1', key2: 'value2']
def dict2 = [key3: 'value3', key4: 'value4']

pipeline {
    agent any
    parameters {
        choice(name: 'dictName', choices: ['dict1', 'dict2'], description: 'Select a dictionary')
    }
    stages {
        stage('Set Variables') {
            steps {
                script {
                    def selectedDict = null
                    switch (params.dictName) {
                        case 'dict1':
                            selectedDict = dict1
                            break
                        case 'dict2':
                            selectedDict = dict2
                            break
                    }
                    for (entry in selectedDict.entrySet()) {
                        env.'${entry.key}' = '${entry.value}'
                    }
                }
            }
        }
        stage('Print Variables') {
            steps {
                echo 'Key1: ${env.key1}'
                echo 'Key2: ${env.key2}'
                echo 'Key3: ${env.key3}'
                echo 'Key4: ${env.key4}'
            }
        }
    }
}

在示例中,我们定义了两个字典 dict1dict2,并使用 parameters 允许用户选择要使用的字典。根据选择的字典名称,switch 语句设置 selectedDict 变量。然后,使用 for 循环遍历 selectedDict 中的每个条目,将其设置为 Jenkins 环境变量。最后,在 Print Variables 阶段打印这些环境变量。

通过这种方法,您可以根据选择的字典设置全局变量,并在 pipeline 的任何部分使用它们。

Jenkinsfile 脚本:使用参数选择字典设置全局变量

原文地址: https://www.cveoy.top/t/topic/n93O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录