Export and import of Jenkins views

tags: jenkins groovy

Written on December 30, 2017

When dealing with jenkins views you will soon realize that this is not that easy as unlike Jenkins jobs or many other configuration stuff, views are not saved in a separate config file or location.

They are embedded the central Jenkins config.xml what makes it a bit more difficult to keep them when rolling out a fresh Jenkins. Therefor I developed a Groovy script that exports the part of the central Jenkins config.xml as plain XML (that can be saved e.g. in a Git-repo):

import groovy.xml.XmlUtil

File centralConfigXmlFile = new File('/data/jenkins/home/config.xml')
File viewsXmlFile = new File ('/tmp/jenkins-views.xml')

def centralConfigXml = new XmlSlurper().parseText(centralConfigXmlFile.text)
def viewsXml = centralConfigXml.views
viewsXmlFile.text = XmlUtil.serialize(viewsXml)

return true

And the counterpart is the import script that writes the given export-file and reloads the instance configuration:

import groovy.xml.XmlUtil

File centralConfigXmlFile = new File('/data/jenkins/home/config.xml')
File viewsXmlFile = new File ('/tmp/jenkins-views.xml')

def centralConfigXml = new XmlSlurper().parseText(centralConfigXmlFile.text)
def viewsXml = new XmlSlurper().parseText(viewsXmlFile.text)
centralConfigXml.views << viewsXml.children()

centralConfigXmlFile.text = XmlUtil.serialize(centralConfigXml)

Jenkins.instance.reload()

return true