该脚本定义了两个字典 ('dict1' 和 'dict2'),并根据参数选择要使用的字典。根据选择的字典名,设置对应的全局变量 ('key1'、'key2' 或 'key3'、'key4'),并将这些变量提供给 pipeline 引用。如果在设置全局变量时没有提供参数值,则使用字典中的默认值。

在第一个阶段中,使用 switch 语句根据选择的字典名设置全局变量。在第二个阶段中,测试全局变量是否设置成功,并输出变量的值。

// 定义多组字典
def dict1 = [
    key1: 'value1',
    key2: 'value2'
]
def dict2 = [
    key3: 'value3',
    key4: 'value4'
]

pipeline {
    agent any
    
    parameters {
        choice(name: 'dictName', choices: ['dict1', 'dict2'], description: 'Choose the dictionary to use')
        string(name: 'key1Value', defaultValue: '', description: 'Enter the value for key1')
        string(name: 'key2Value', defaultValue: '', description: 'Enter the value for key2')
        string(name: 'key3Value', defaultValue: '', description: 'Enter the value for key3')
        string(name: 'key4Value', defaultValue: '', description: 'Enter the value for key4')
    }
    
    stages {
        stage('Set globals') {
            steps {
                script {
                    // 根据选择的字典名设置全局变量
                    switch (params.dictName) {
                        case 'dict1':
                            global.key1 = key1Value ?: dict1.key1
                            global.key2 = key2Value ?: dict1.key2
                            break
                        case 'dict2':
                            global.key3 = key3Value ?: dict2.key3
                            global.key4 = key4Value ?: dict2.key4
                            break
                    }
                }
            }
        }
        
        stage('Test globals') {
            steps {
                script {
                    // 测试全局变量是否设置成功
                    switch (params.dictName) {
                        case 'dict1':
                            echo 'key1=${global.key1}, key2=${global.key2}'
                            assert global.key1 == dict1.key1
                            assert global.key2 == dict1.key2
                            break
                        case 'dict2':
                            echo 'key3=${global.key3}, key4=${global.key4}'
                            assert global.key3 == dict2.key3
                            assert global.key4 == dict2.key4
                            break
                    }
                }
            }
        }
    }
}
Jenkinsfile 脚本:使用参数选择字典并设置全局变量

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

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