Search code examples
jenkinsjenkins-pluginsjenkins-job-dsl

how do I create a job that runs groovy code with the job dsl?


I can run this inside of a job dsl project:

def pluginsListFile = new File("${plugins}/plugins.txt")
def pluginsList = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
pluginsList.each {
    pluginsListFile.append "${it.getShortName()}: ${it.getVersion()}\n"
}

But I want the job dsl script to create a job that runs this groovy code (on a schedule). It looked like systemGroovyCommand is what I would use be I dont understand- looks like you have to use a .groovy file for systemGroovyCommand which i would like to avoid.


Solution

  • Yes, it's systemGroovyCommand. You don't have to store this script in separate file, but it's a best practice. systemGroovyCommand accepts string as parameter, so you can pass your code this way, but remember to escape special characters.

    Example usage:

    def script = '''
    def pluginsListFile = new File("${plugins}/plugins.txt")
    def pluginsList = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
    pluginsList.each {
        pluginsListFile.append "${it.getShortName()}: ${it.getVersion()}\\n"
    }
    '''
    job('TEST_JOB_SCRIPT') {
        steps {
            systemGroovyCommand(script)
        }
    }