Skip to content

Instantly share code, notes, and snippets.

@ivan-pinatti
Last active November 27, 2024 12:05
Show Gist options
  • Save ivan-pinatti/454846b24987148803cf80bcd74ef562 to your computer and use it in GitHub Desktop.
Save ivan-pinatti/454846b24987148803cf80bcd74ef562 to your computer and use it in GitHub Desktop.
Jenkins - Create a Jenkins view via groovy script - #jenkins #groovy #jenkins-view
#!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()
@sbahore
Copy link

sbahore commented Oct 28, 2022

Hi Guyz,
I have a similar case where I need to update my view with job name but instead of hardcoding the job name, I want to give regular expression which will includes the job.
How can I do that?
Thank you in advance!
image

@ivan-pinatti
Copy link
Author

Hi @sbahore,

I don't have an answer for this scenario, it would require some investigation. I would suggest that you explore the view classes and methods, a good starting point is; https://github.com/jenkinsci/jenkins/tree/master/core/src/main/java/hudson/views

I hope it helps.

@lycofron
Copy link

I just managed to add a regular expression filter to the view, here is how I did it:

def jobRegex = ".*" 

// Configure regex-based job filter
def regexJobFilter = new hudson.views.RegExJobFilter(
    jobRegex, // regex
    "includeMatched", // includeExcludeTypeString
    "NAME" // valueTypeString
)

// Add the filter to the view
def jobFilters = newView.jobFilters ?: []
jobFilters.add(regexJobFilter)
newView.jobFilters = jobFilters

// Save the view
newView.save()

To see allowed values, check documentation:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment