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()
@Vamsi3012
Copy link

Hi,

Firstly, thank you for the example. Could you please elaborate this example for checking if the view already exists and only then creating the view? The current example creates new views always instead of updating the existing view.

Thanks in advance :)

Best Regards,
Vamsi

@ivan-pinatti
Copy link
Author

Hi @Vamsi3012,

Thanks for your comment.

IIRC, it updates the view as well. I don't have an instance to test it right now, however, you can find some info on it in the official documentation/code; https://github.com/jenkinsci/jenkins/blob/22aa2e6e766074d11249893e3f35e0b99e20d3d0/test/src/test/java/hudson/cli/UpdateViewCommandTest.java

I hope it helps! :)

Cheers!

@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