首页 > 解决方案 > 如何通过 Configuration as code 创建 jenkins pipelineJob?

问题描述

我想使用脚本在我的 Jenkins 配置中创建一个简单的管道作业。所以我的 jenkins.yaml 文件如下:

 jobs:
  - script: >
      pipelineJob('Tag Repositories') {
        definition {
          cps {
            def theScript = readFileFromWorkspace('git_tag_job.groovy')
            script(theScript)
            sandbox()
          }
        }
      }

所以我认为该文件git_tag_job.groovy可以在 Jenkins 主目录中,但看起来 readFileFromWorkspace 正在查看尚未创建的该作业的工作区。结果,我收到 NPE 错误,因为工作空间为空。

现在的问题是如何使用 Configuration As Code 插件来添加这个作业,并将其内容git_tag_job.groovy作为其脚本?

脚本很大,我不能把它放在 Yaml 文件中。

令我感到奇怪的是,如果我们无法从某个地方加载脚本,那么这种配置和 readFileFromWorkspace 就毫无用处,因为您很少有使用单行脚本的管道作业,因此从文件加载是唯一实用的选择。

我在这里错过了什么还是有其他方法可以做到这一点?

标签: jenkinsjenkins-pluginsjenkins-job-dsljcasc

解决方案


我知道这是一个老问题,但我遇到了完全相同的问题,所以这里有一个解决方案,遵循@xbmono 对任何在这里绊倒的人的评论:

我选择将种子作业 dsl 脚本与 yaml 文件分开,但基本相同。

casc.yaml

...
jobs:
  -file: /abs/path/to/seedjob.groovy

种子作业.groovy

theScript = new File('/abs/path/to/git_tag_job.groovy').getText("UTF-8")
pipelineJob('Tag Repositories') {
  definition {
    cps {
      script(theScript)
      sandbox()
    }
  }
}


推荐阅读