如何将 Jenkins DSL 文件重写为 Jenkins 管道 jenkinsfile?

How to re-write a Jenkins DSL file as a Jenkins pipeline jenkinsfile?

我有以下 Jenkins DSL 文件:

if (params["BUILD_SNAPSHOT"] == "true") {
    parallel(
        {
            build("company-main-build-snapshot")
        },
        {
            build("1-company-worker-build-snaphsot", WORKER_NAME: "sharding-worker")
        }
    )
}
parallel (
    {
        build("company-deployment-info",
            API_KEY: "aaaaa5dd4cd58b94215f9cddd4441c391b4ddde226ede98",
            APP: "company-Staging-App")
    },
    {
        build("company-salt-role-deploy",
                ENV: "staging",
                ROLE: "app")
    },
    {
        build("company-deployment-info",
            API_KEY: "aaaaa5dd4cd58b94215f9cddd4441c391b4ddde226ede98",
            APP: "company-Staging-Shardwork")
    },
    {
        build("company-salt-workers-deploy",
                ENVIRONMENT: "staging",
                WORKER_TYPE: "shardwork")
    }
)

if (params["REST_TEST"] == "true") {
    build("company_STAGING_python_rest_test")
}

我的任务是convert/rewrite这个工作流文件内容到Jenkins管道Jenkinsfile。

我有一些示例文件供参考,但我很难理解我应该如何开始...

任何人都可以阐明这个主题吗?

先好好看看Jenkins pipeline documentation, it is a great start and it is providing a whole bunch of information such as Build Parameters usage or parallel steps

这里还有一些提示供您探索:

参数

只需将参数名作为变量即可如:

if (BUILD_SNAPSHOT) {
    ...
}

调用其他作业

您还可以使用构建步骤,例如:

build job: '1-company-worker-build-snaphsot', parameters: [stringParam(name: 'WORKER_NAME', value: "sharding-worker")]

使用函数

与其每次都使用构建步骤调用下游作业,不如考虑使用来自另一个 Groovy 脚本的管道函数,可以来自您当前的项目,甚至来自外部,签出 Groovy 脚本。

例如,您可以将您的第二个求职电话替换为:

build("1-company-worker-build-snaphsot", WORKER_NAME: "sharding-worker")

至:

git 'http://urlToYourGit/projectContainingYourScript'
pipeline = load 'global-functions.groovy'
pipeline.buildSnapshot("sharding-worker")

...当然,初始化阶段(Git 校验和管道加载)只需要一次就可以调用所有外部脚本函数。

简而言之

总结一下,您的代码可以转换为以下内容:

node {
    git 'http://urlToYourGit/projectContainingYourScript'
    pipeline = load 'global-functions.groovy'

    if(BUILD_SNAPSHOT) {
        parallel (
            phase1: { pipeline.buildMainSnapshot() },
            phase2: { pipeline.buildWorkerSnapshot("sharding-worker") }
        )
    }
    parallel (
        phase1: { pipeline.phase1(params...) },
        phase2: { pipeline.phase2(params...) },
        phase3: { pipeline.phase3(params...) },
        phase4: { pipeline.phase4(params...) }
    )
    if (REST_TEST) {
        pipeline.finalStep()
    }
}