文章

Jenkins特殊流水线使用

1. 动态设置参数

1.1 Jenkins job 创建流水线

Image

1.2 设置job参数

1
2
3
4
5
6
7
1. 添加 Pipline 中引用的必要的参数
参数化构建过程 --> 添加参数 --> [字符参数|选择参数|...]

备注: 
1. 在pipline中动态生成的参数可以不需要添加

2. 其他默认,或根据需要填写

1.3 设置流水线

流水线模版如下

1
2
3
4
5
6
7
8
备注: 
1. 动态参数设置返回的结果是一列数据,不是列表,如下:
check_old_data
delete_asst_inst
get_inst_info
update_inst

2. Pipline中执行脚本时注意转义: $、'、" 等特殊符号

Pipline模版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
pipeline {
    agent { label 'devops' }

    options {
        timestamps()
    }
    environment {
        HTTP_BLUEKING_TOKEN=credentials('CMDB_TOKEN')
    }
    post {
        always {
            cleanWs()
        }
    }
    stages {
        stage('Prepare Parameters') {
            steps {
                script {
                    // 执行 shell 脚本并捕获输出
                    // 假设输出是以换行符分隔的多个值
                    def output = sh(script: '''
                        source /devops/script/setup.sh && script_sync master >/dev/null 2>&1
                        [ -d /tmp/cmdb-sdk-python ] && rm -rf /tmp/cmdb-sdk-python
                        git clone -b \$cmdb_task_branch git@gitlab.abc.cn:dev/cmdb-sdk-python.git /tmp/cmdb-sdk-python
                        python3 /tmp/cmdb-sdk-python/cli_xt_prod_tasks/ops.py -h | python3 -c \"import sys; help_text=sys.stdin.read(); print(help_text.split(\'positional arguments:\')[1].split(\'\\n\')[1].strip()[1:-1].replace(\',\', \'\\n\'))\"
                    ''', returnStdout: true).trim()
                    
                    // 将输出转换为列表
                    def options = output.split('\n')
                    
                    // 打印输出以便调试
                    echo "Dynamic Options: ${options}"
                    
                    // 动态设置参数
                    properties([
                        parameters([
                            string(name:'nsname', defaultValue: '', description: '环境名'),
                            choice(name: 'Field', choices: options.join('\n'), description: '执行方法'),
                            string(name:'ops_script_branch', defaultValue: 'master', description: '分支')
                        ])
                        
                    ])
                }
            }
        }
        
    }
}

1.4 使动态参数生效

1
2
3
4
5
1. 保存流水线

2. 手动触发: Build with Parameters --> Build

3. 参数就会自动填充至参数列表中
本文由作者按照 CC BY 4.0 进行授权