在编写jenkins管道时,提交每个新更改以查看它是否有效似乎非常不方便。

是否有一种方法可以在本地执行这些而不提交代码?


当前回答

这是一个简短的解决方案,可以让我非常快速地测试管道代码:

pipeline {
    agent any
    options {
        skipDefaultCheckout true
        timestamps()
    }
    parameters {
        text(name: 'SCRIPT', defaultValue: params.SCRIPT,
            description: 'Groovy script')
    }
    stages {
        stage("main") {
            steps {
                script {
                    writeFile file: 'script.groovy', 
                        text: params.SCRIPT
                    def groovyScript = load 'script.groovy'
                    echo "Return value: " + groovyScript
                }
            } // steps
        } // stage
    } // stages
} // pipeline

skipDefaultCheckout为true,因为我们不需要这个工具git存储库中的文件。 defaultValue:参数。SCRIPT将默认值设置为最近一次执行。如果只有一个用户使用,它允许非常快速的短测试周期。 给定的脚本被写入一个文件,并加载和加载。

有了这个设置,我可以在其他jenkins文件中测试我能做的所有事情,包括使用共享库。

其他回答

有点晚了,但这就是为什么我写了jenny,一个小的重新实现一些核心的Jenkinsfile步骤。(https://github.com/bmustiata/jenny)

您可以验证您的管道以找出语法问题。Jenkins有很好的用于Jenkisfile验证的API - https://jenkins_url/pipeline-model-converter/validate

使用curl并传递.Jenkinsfile,您将立即得到语法检查

curl --user username:password -X POST -F "jenkinsfile=<jenkinsfile" https://jenkins_url/pipeline-model-converter/validate

您可以将此工作流添加到编辑器:

VS代码 崇高的文本

除了其他人已经提到的重放功能(关于它的有用性也一样!),我发现以下功能也很有用:

创建一个测试管道作业,您可以在其中键入管道代码或指向Jenkinsfile的repo/分支来快速测试一些东西。为了更准确的测试,使用Multibranch Pipeline,它指向你自己的fork,在那里你可以快速做出改变并提交,而不影响proch。 由于Jenkinsfile是Groovy代码,只需使用“Groovy Jenkinsfile”调用它来验证基本语法。

博士TL;

Jenkins Pipeline单元测试框架 Jenkinsfile跑步

长版本 管道测试越来越让人头疼。不同于经典的声明式作业配置方法(其中用户仅限于UI所公开的内容),新的Jenkins Pipeline是一种用于构建过程的成熟编程语言,您可以将声明式部分与自己的代码混合在一起。作为优秀的开发人员,我们也希望对这类代码进行单元测试。

在开发Jenkins pipeline时,您应该遵循三个步骤。第一步。应该覆盖80%的用例。

Do as much as possible in build scripts (eg. Maven, Gradle, Gulp etc.). Then in your pipeline scripts just calls the build tasks in the right order. The build pipeline just orchestrates and executes the build tasks but does not have any major logic that needs a special testing. If the previous rule can't be fully applied then move over to Pipeline Shared libraries where you can develop and test custom logic on its own and integrate them into the pipeline. If all of the above fails you, you can try one of those libraries that came up recently (March-2017). Jenkins Pipeline Unit testing framework or pipelineUnit (examples). Since 2018 there is also Jenkinsfile Runner, a package to execution Jenkins pipelines from a command line tool.

例子

pipelineUnit GitHub回购包含了一些关于如何使用Jenkins Pipeline Unit测试框架的Spock示例

在撰写本文时(2017年7月底),使用Blue Ocean插件,您可以直接在可视化管道编辑器中检查声明式管道的语法。当你点击“配置”时,编辑器从蓝海UI工作,仅用于github项目(这是一个已知的问题,他们正在努力使它也适用于git等)。

但是,正如在这个问题中解释的那样,你可以打开编辑器浏览到:

詹金斯[URL] /蓝色/组织/ Jenkins / pipeline-editor /

然后单击页面中间,并按Ctrl+S,这将打开一个文本区域,您可以在其中粘贴管道声明性脚本。当您单击Update时,如果有语法错误,编辑器将告诉您语法错误在哪里。就像这张截图:

如果没有语法错误,文本区域将关闭,页面将显示您的管道。别担心,它不会保存任何东西(如果它是一个github项目,它会提交Jenkinsfile更改)。

我是Jenkins的新手,这是非常有用的,没有这个,我不得不多次提交一个Jenkins文件,直到它工作(非常讨厌!)希望这能有所帮助。欢呼。