如何创建一个运行 groovy 代码和作业 dsl 的作业?

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

我可以 运行 在工作 dsl 项目中这样做:

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

但我希望作业 dsl 脚本创建 运行 这个 groovy 代码的作业(按计划)。看起来 systemGroovyCommand 是我会使用的,但我不明白 - 看起来你必须使用 .groovy file 作为我想避免的 systemGroovyCommand。

是的,是 systemGroovyCommand。您不必将此脚本存储在单独的文件中,但这是最佳做法。 systemGroovyCommand 接受字符串作为参数,因此您可以通过这种方式传递代码,但请记住对特殊字符进行转义。

用法示例:

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)
    }
}