zoukankan      html  css  js  c++  java
  • Programatically manage Jenkins Jobs by Groovy code

    背景

    同一个Jenkins服务器上,存在的Job越多,越需要进行归类管理。

    View -- 分类

    https://subscription.packtpub.com/book/application_development/9781784390891/3/ch03lvl1sec22/creating-views

    Views in Jenkins allow us to organize jobs and content into tabbed categories, which are displayed on the main dashboard. As a Jenkins instance expands, it is logical to create associated views for appropriate groups and categories. For example it may be a good idea to create a Build view, which displays build-specific jobs within it. Let's spend a few minutes discovering how to implement a new view within Jenkins and learn ways to filter its content.

    To implement a new view, there is a tab icon with a plus sign located on the main Jenkins dashboard, as illustrated in Figure 3-14:

    Figure 3-14: Creating a new view

    Groovy -- 从view中删除job

    https://gist.github.com/obcode/63d9ddd7a239c9f3b020

    import hudson.model.ListView
    import jenkins.model.*
    
    // Begin Parameters
    view_name = "braun-sweng";
    // End Parameters
    
    vc = Jenkins.instance.getView(view_name).getOwner();
    
    v = vc.getView(view_name);
    
    for(job in v.getItems()) {
      print "removing $job \n"
      job.delete();
    }
    
    vc.deleteView(v);
    print "$view_name removed \n";

    Groovy -- 添加Job到view

    https://gist.github.com/ivan-pinatti/454846b24987148803cf80bcd74ef562

    #!groovy
    
    // imports
    import jenkins.model.Jenkins
    import hudson.model.ListView
    
    // get Jenkins instance
    Jenkins jenkins = Jenkins.getInstance()
    
    // variables
    def viewName = 'MyView'
    
    // create the new view
    jenkins.addView(new ListView(viewName))
    
    // get the view
    myView = hudson.model.Hudson.instance.getView(viewName)
    
    // add a job by its name
    myView.doAddJobToView('MyJob1')
    myView.doAddJobToView('MyJob2')
    myView.doAddJobToView('MyJob3')
    
    // save current Jenkins state to disk
    jenkins.save()

    cloudbees - Folder分类

    https://docs.cloudbees.com/docs/admin-resources/latest/plugins/folder

    The Folders plugin allows you to organize jobs in hierarchical folders, much like how you organize files in directories in your file system.

    While this plugin is now open source, it is a foundational element of CloudBees CI, CloudBees Jenkins Platform, CloudBees Jenkins Distribution, and CloudBees Jenkins Enterprise.

    Jenkins has limited capacity for organizing a large number of jobs or organizing jobs around taxonomies such as projects or departments. Today, most teams group jobs around views on the dashboard, but views are not optimal for understanding custom taxonomies. The Folders plugin addresses this limitation because it helps capture taxonomies in a user environment and helps organize jobs around these taxonomies.

    The Folders plugin enables you to create a folder and group related jobs together. These jobs can be organized around a project, department, sub-department, release or any taxonomy that you choose to define. You can create an arbitrary level of nested folders. Folders are namespace aware, so Job A in Folder A is logically different from Job A in Folder B

    The Folders plugin allows you to clone a folder with its children intact. This is useful to seed new projects or jobs with information from a particular project type. Folders can also define properties that are visible to jobs inside them, enabling you to simplify branch and pipeline management.

    Groovy -- add folder

    https://github.com/peterjenkins1/jenkins-scripts/blob/master/add-folder.groovy

    /*
    This adds a folder.
    Because we have jobs with the same name as the environments, this code also renames
    the folder. That extra code can be removed once this is deployed to jenkins1.
    Another temp feature is moving the existing jobs into the folder.
    */
    import com.cloudbees.hudson.plugins.folder.*
    import org.jenkinsci.plugins.workflow.job.WorkflowJob
    import jenkins.model.Jenkins
    
    Jenkins jenkins = Jenkins.instance // saves some typing
    
    // Bring some values in from ansible using the jenkins_script modules wierd "args" approach (these are not gstrings)
    String folderName = "$folderName"
    String folderNameTemp = folderName + "-folder"
    
    def folder = jenkins.getItem(folderName)
    if (folder == null) {
      // Create the folder if it doesn't exist or if no existing job has the same name
      folder = jenkins.createProject(Folder.class, folderName)
    } else {
      if (folder.getClass() != Folder.class) {
        // when folderName exists, but is not a folder we make the folder with a temp name
        folder = jenkins.createProject(Folder.class, folderNameTemp)
        // Move existing jobs from the same environment to folders (preseve history)
        Item[] items = jenkins.getItems(WorkflowJob.class)
        def job_regex = "^" + folderName
    
        items.grep { it.name =~ job_regex }.each { job ->
          Items.move(job, folder)
        }
    
        // Rename the temp folder now we've moved the jobs
        folder.renameTo(folderName)
      }
    }

    Groovy -- add job to folder

    https://github.com/peterjenkins1/jenkins-scripts/blob/master/add-job.groovy

    // Adds a pipeline job to jenkins
    import jenkins.model.Jenkins
    import org.jenkinsci.plugins.workflow.job.WorkflowJob
    import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
    import org.jenkinsci.plugins.workflow.flow.FlowDefinition
    import hudson.plugins.git.GitSCM
    import hudson.plugins.git.UserRemoteConfig
    import com.cloudbees.hudson.plugins.folder.*
    
    // Bring some values in from ansible using the jenkins_script modules wierd "args" approach (these are not gstrings)
    String folderName = "$folderName"
    String jobName = "$jobName"
    String jobScript = "$jobScript"
    String gitRepo = "$gitRepo"
    String gitRepoName = "$gitRepoName"
    String credentialsId = "$credentialsId"
    
    Jenkins jenkins = Jenkins.instance // saves some typing
    
    // Get the folder where this job should be
    def folder = jenkins.getItem(folderName)
    // Create the folder if it doesn't exist
    if (folder == null) {
      folder = jenkins.createProject(Folder.class, folderName)
    }
    
    // Create the git configuration
    UserRemoteConfig userRemoteConfig = new UserRemoteConfig(gitRepo, gitRepoName, null, credentialsId)
    
    branches = null
    doGenerateSubmoduleConfigurations = false
    submoduleCfg = null
    browser = null
    gitTool = null
    extensions = []
    GitSCM scm = new GitSCM([userRemoteConfig], branches, doGenerateSubmoduleConfigurations, submoduleCfg, browser, gitTool, extensions)
    
    // Create the workflow
    FlowDefinition flowDefinition = (FlowDefinition) new CpsScmFlowDefinition(scm, jobScript)
    
    // Check if the job already exists
    Object job = null
    job = folder.getItem(jobName)
    if (job == null) {
      oldJob = jenkins.getItem(jobName)
      if (oldJob.getClass() == WorkflowJob.class) {
        // Move any existing job into the folder
        Items.move(oldJob, folder)
      } else {
        // Create it if it doesn't
        job = folder.createProject(WorkflowJob, jobName)
      }
    }
    // Add the workflow to the job
    job.setDefinition(flowDefinition)
    
    // Set the branch somehow
    job.save()

    Reference

    list jobs

    https://support.cloudbees.com/hc/en-us/articles/226941767-Groovy-to-list-all-jobs

    Go to Script Console under Manage Jenkins, this script will print the name of all jobs including jobs inside of a folder and the folders themselves:

    Jenkins.instance.getAllItems(AbstractItem.class).each {
        println it.fullName + " - " + it.class
    };
    

    This script will print the name of all jobs including jobs inside of a folder, but not the folders themselves.

    Jenkins.instance.getAllItems(Job.class).each{ 
        println it.name + " - " + it.class
    }
    

    This script will recursively print the name of all jobs implementing the AbstractProject class, i.e. Freestyle and Maven jobs.

    Jenkins.instance.getAllItems(AbstractProject.class).each {it ->
        println it.fullName;
    }
    

    This script will recursively print the name of all the Multibranch jobs.

    Jenkins.instance.getAllItems(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject).each {it ->
        println it.fullName;
    }
    

    create pipeline logic

    https://github.com/YAwasom/project/blob/ba15d0ed98e49668d85dc6c3347a1e7dd9d38138/ops/jenkins/jcasc/seed/seed.groovy

    出处:http://www.cnblogs.com/lightsong/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
  • 相关阅读:
    vue调用嵌套iframe的方法
    Kafaka 集群搭建(Windows环境)
    EF Core 延迟加载
    OLTP 和 OLAP
    数据库调优(二)Inner Join Merge Join Hash Match
    数据库性能调优(一)
    Identity Server4 数据迁移、持久化
    mysql.data.entityframeworkcore 已弃用
    Failed to start LSB: Bring up/down networking
    线程死锁与同步
  • 原文地址:https://www.cnblogs.com/lightsong/p/15688882.html
Copyright © 2011-2022 走看看