如何在 Jenkins 管道中加载 bash 脚本?

Den*_*boy 7 bash jenkins jenkins-pipeline

我们有一些复杂的 bash 脚本,现在位于 Jenkins 的托管文件部分。我们尝试将作业迁移到管道,但我们不知道将 bash 脚本转换为 groovy,因此我们希望将其保留在 bash 中。我们在 Git 中有一个 jenkins-shared-library,我们在其中存储我们的管道模板。在作业中,我们添加了正确的环境变量。

我们希望将 bash 脚本保存在 git 中而不是托管文件中。在管道中加载此脚本并执行它的正确方法是什么?我们用 尝试了一些东西libraryResource,但我们没有设法让它工作。我们必须将test.sh脚本放在 git 中的什么位置以及如何调用它?(或者在这里运行shell脚本是完全错误的)

def call(body) {
    // evaluate the body block, and collect configuration into the object
    def pipelineParams= [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = pipelineParams
    body()

    pipeline {
        agent any

        options {
            buildDiscarder(logRotator(numToKeepStr: '3'))
        }

        stages {

            stage ('ExecuteTestScript') {
                steps {
                    def script = libraryResource 'loadtestscript?'

                    script {
                        sh './test.sh'
                    }
                }
            }

        }

        post {
            always {
                cleanWs()
            }

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*zon 5

在我的公司,我们的 CI 中也有复杂的 bash 脚本,这libraryResource是一个更好的解决方案。按照您的脚本,您可以执行一些更改以使用bash存储到的脚本libraryResource

stages {
    stage ('ExecuteTestScript') {
        steps {
            // Load script from library with package path
            def script_bash = libraryResource 'com/example/loadtestscript'

            // create a file with script_bash content
            writeFile file: './test.sh', text: script_bash

            // Run it!
            sh 'bash ./test.sh'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)