Jenkins插件:从JSON文件加载Extended Choice参数

145次阅读
没有评论

问题描述

在Jenkins构建作业中使用了Extended Choice Parameter插件,并成功添加了普通参数和Extended Choice参数。但是,他想要能够从JSON文件中动态加载参数。他想知道如何修改上述脚本来实现这一目标。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

你可以使用Extended Choice Parameter插件的javascriptFile参数来从JSON文件中加载参数。以下是修改后的示例脚本:

properties([
    [$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '500']],
    parameters([
        extendedChoice(
            defaultValue: 'One,Two,Three,Four',
            description: '',
            javascriptFile: '/path/to/file.json',
            multiSelectDelimiter: ',',
            name: 'SAMPLE_EXTENDED_CHOICE',
            quoteValue: false,
            saveJSONParameterToFile: false,
            type: 'PT_JSON',
            value: 'One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten',
            visibleItemCount: 10
        )
    ])
])

在上面的示例中,我们添加了javascriptFile参数,并将type设置为PT_JSON。你需要将javascriptFile参数的值设置为指向你的JSON文件的路径。
请确保JSON文件存在,并且Jenkins服务器可以访问到该文件。

方案2

如果你的JSON文件位于正在构建的相同代码库中,你可以使用Jenkins的checkout步骤来检出代码库,并使用readJSON()步骤来读取JSON文件。以下是修改后的示例脚本:

properties([
    [$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '500']],
    parameters([
        extendedChoice(
            defaultValue: 'One,Two,Three,Four',
            description: '',
            javascriptFile: "${WORKSPACE}/path/to/file.json",
            multiSelectDelimiter: ',',
            name: 'SAMPLE_EXTENDED_CHOICE',
            quoteValue: false,
            saveJSONParameterToFile: false,
            type: 'PT_JSON',
            value: 'One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten',
            visibleItemCount: 10
        )
    ])
])

在上面的示例中,我们使用${WORKSPACE}变量来指定JSON文件的路径。${WORKSPACE}变量是Jenkins中的一个环境变量,表示当前构建的工作空间目录。
请确保JSON文件位于代码库中的正确路径,并且Jenkins服务器可以访问到该文件。

方案3

如果你的JSON文件是通过Groovy脚本生成的,你可以使用Groovy脚本选项来返回一个JSON对象。以下是修改后的示例脚本:

properties([
    [$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '500']],
    parameters([
        extendedChoice(
            defaultValue: 'One,Two,Three,Four',
            description: '',
            groovyClasspath: '',
            groovyScript: '''
                import org.boon.Boon;
                def data = new File('data_from_eric.json').getText('UTF-8');
                def jsonEditorOptions = Boon.fromJson('${data}');
                return jsonEditorOptions;
            ''',
            multiSelectDelimiter: ',',
            name: 'Policy12345',
            quoteValue: false,
            saveJSONParameterToFile: false,
            type: 'PT_JSON',
            visibleItemCount: 5
        )
    ])
])

在上面的示例中,我们使用Groovy脚本来读取JSON文件,并将其转换为JSON对象。你需要将groovyScript参数中的文件路径修改为你的JSON文件的路径。
请确保Groovy脚本可以访问到JSON文件,并且JSON文件的格式正确。
以上是几种从JSON文件加载Extended Choice参数的解决方案。根据你的具体需求和环境,选择适合你的方案即可。

正文完