在大规模的Jenkins实践中创建项目也是一个问题,如何通过模板自动化的创建Jenkins项目呢? 可以通过安装Job Dsl插件后,通过 Dsl直接创建项目。也可以通过工具将dsl转换为xml,然后再通过Jenkins API创建项目。相对比较第一种方式更加直接一些,由于时间问题今天暂时分享第二种创建项目的方式。

创新互联于2013年开始,是专业互联网技术服务公司,拥有项目网站设计、成都做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元湛江做网站,已为上家服务,为湛江各地企业和个人服务,联系电话:18982081108
1.根据Job DSL API生成模板
我们需要先安装好Job Dsl 插件,然后执行DSL创建项目。地址:https://jenkinsci.github.io/job-dsl-plugin/
例如: 使用官网的example。这里定义了一个流水线项目,配置了项目的信息包括(项目描述、项目参数、Jenkinsfile地址)
- pipelineJob("test-schdule-service") {
 - description("this is my first job")
 - keepDependencies(false)
 - parameters {
 - choiceParam("test", [1, 2, 3], "")
 - }
 - definition {
 - cpsScm {
 - scm {
 - git {
 - remote {
 - github("https://gitlab.com/xxx/xxx.git", "https")
 - credentials("24982560-17fc-4589-819b-bc5bea89da77")
 - }
 - branch("*/master")
 - }
 - }
 - scriptPath("Jenkinsfile")
 - }
 - }
 - disabled(false)
 - }
 
2.通过Playground转换DSL -> XML
url: http://job-dsl.herokuapp.com/
3.通过Jenkins Core Api创建项目
- import javax.xml.transform.stream.StreamSource
 - import jenkins.model.Jenkins
 - //创建项目
 - void createOrUpdateJob(String name, String xml) {
 - def j = Jenkins.instance
 - String fullName = name
 - if(name.contains('/')) {
 - j = j.getItemByFullName(name.tokenize('/')[0..-2])
 - name = name.tokenize('/')[-1]
 - }
 - Jenkins.checkGoodName(name)
 - if(j.getItem(name) == null) {
 - println "Created job \"${fullName}\"."
 - j.createProjectFromXML(name, new ByteArrayInputStream(xml.getBytes()))
 - j.save()
 - }
 - else if(j.getItem(name).configFile.asString().trim() != xml.trim()) {
 - j.getItem(name).updateByXml(new StreamSource(new ByteArrayInputStream(xml.getBytes())))
 - j.getItem(name).save()
 - println "Job \"${fullName}\" already exists. Updated using XML."
 - }
 - else {
 - println "Nothing changed. Job \"${fullName}\" already exists."
 - }
 - }
 - try {
 - //just by trying to access properties should throw an exception
 - itemName == null
 - xmlData == null
 - isPropertiesSet = true
 - } catch(MissingPropertyException e) {
 - println 'ERROR Can\'t create job.'
 - println 'ERROR Missing properties: itemName, xmlData'
 - return
 - }
 - String xmlData = """
 this is my first job false 1 2 3 test https://github.com/https://gitlab.com/xxx/xxx.git/ Jenkinsfile false https://github.com/https://gitlab.com/xxx/xxx.git.git 24982560-17fc-4589-819b-bc5bea89da77 */master 2 false Default https://github.com/https://gitlab.com/xxx/xxx.git/ false - """
 - String itemName = "my-first-pipeline"
 - createOrUpdateJob(itemName, xmlData)
 
4.通过Jenkins Script Console运行
创建完成
            
            分享文章:实践:JenkinsCoreApi&JobDSL创建项目            
            网址分享:http://wtcwzsj.com/article/cdjisij.html
        
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号