简体   繁体   English

Jenkins Groovy Postbuild使用静态文件而不是脚本

[英]Jenkins Groovy Postbuild use static file instead of script

Is it possible to load an external groovy script into the groovy post build plugin instead of pasting the script content into each job? 是否可以将外部groovy脚本加载到groovy post build插件中,而不是将脚本内容粘贴到每个作业中? We have approximately 200 jobs so updating them all is rather time consuming. 我们有大约200个工作岗位,因此更新所有工作相当费时。 I know that I could write a script to update the config files directly (as in this post: Add Jenkins Groovy Postbuild step to all jobs ), but these jobs run 24x7 so finding a window when I can restart Jenkins or reload the config is problematic. 我知道我可以编写一个脚本来直接更新配置文件(如本文所示: 将Jenkins Groovy Postbuild步骤添加到所有作业 ),但这些作业全天候运行,因此当我可以重新启动Jenkins或重新加载配置时找到一个窗口是有问题的。

Thanks! 谢谢!

Update : This is what really solved it for me: https://issues.jenkins-ci.org/browse/JENKINS-21480 更新 :这是我真正解决的问题: https//issues.jenkins-ci.org/browse/JENKINS-21480

"I am able to do just that by doing the following. Enter these lines in lieu of the script in the "Groovy script" box:" “我可以通过执行以下操作来做到这一点。在”Groovy脚本“框中输入这些代替脚本:”

// Delegate to an external script
// The filename must match the class name
import JenkinsPostBuild
def postBuild = new JenkinsPostBuild(manager)
postBuild.run()

"Then in the "Additional groovy classpath" box enter the path to that file." “然后在”Additional groovy classpath“框中输入该文件的路径。”

Just put the following in the "Groovy script:" field: 只需将以下内容放在“Groovy脚本:”字段中:

evaluate(new File("... groovy script file name ...")); evaluate(new File(“... groovy script file name ...”));

Also, you might want to go even further. 此外,您可能想要更进一步。 What if script name or path changes? 如果脚本名称或路径发生变化怎么办 Using Template plugin you can create a single "template" job, define call to groovy script (above line) in there, and in all jobs that need it add post-build action called "Use publishers from another project" referencing this template project. 使用模板插件,您可以创建一个“模板”作业,在那里定义对groovy脚本(上面一行)的调用,并在需要它的所有作业中添加引用此模板项目的名为“使用另一个项目的发布者”的构建后操作。

We do it in the following fashion. 我们以下列方式进行。

We have a file c:\\somepath\\MyScriptLibClass.groovy (accessible for Jenkins) which contains code of a groovy class MyScriptLibClass. 我们有一个文件c:\\somepath\\MyScriptLibClass.groovy (Jenkins可访问),它包含一个groovy类MyScriptLibClass的代码。 The class contains a number of functions designed to act like static methods (to be mixed in later). 该类包含许多设计用于静态方法的函数(稍后将混合使用)。

We include this functions writing the following statement in the beginning of sytem groovy and postbuild groovy steps: 我们在sytem groovy和postbuild groovy步骤的开头包含了这个函数编写以下语句:

[ // include lib scripts
    'MyScriptLibClass'
].each{ this.metaClass.mixin(new GroovyScriptEngine('c:\\somepath').loadScriptByName(it+'.groovy')) }

This could look a bit ugly but you need to write it only once for script. 这可能看起来有点难看,但你只需要为脚本编写一次。 You could include more than one script and also use inheritance between library classes. 您可以包含多个脚本,也可以在库类之间使用继承。

Here you see that all methods from the library class are mixed in the current script. 在这里,您可以看到库类中的所有方法都混合在当前脚本中。 So if your class looks like: 所以,如果你的班级如下:

class MyScriptLibClass {
    def setBuildName( String str ){
        binding?.variables['manager'].build.displayName = str
    }
}

in Groovy Postbuild you could write just: 在Groovy Postbuild中你可以写:

[ // include lib scripts
    'MyScriptLibClass'
].each{ this.metaClass.mixin(new GroovyScriptEngine('c:\\somepath').loadScriptByName(it+'.groovy')) }

setBuildName( 'My Greatest Build' )

and it will change your current build's name. 它会改变你当前版本的名称。

There are also other ways to load external groovy classes and it is not necessary to use mixing in. For instance you can take a look here Compiling and using Groovy classes from Java at runtime? 还有其他方法可以加载外部groovy类,并且没有必要使用混合。例如,您可以看一下在运行时从Java编译和使用Groovy类?

How did I solve this: 我是怎么解决的:

Create file $JENKINS_HOME/scripts/PostbuildActions.groovy with following content: 使用以下内容创建文件$ JENKINS_HOME / scripts / PostbuildActions.groovy:

public class PostbuildActions {
  void setBuildName(Object manager, String str ){
    binding?.variables['manager'].build.displayName = str
  }
}

In this case in Groovy Postbuild you could write: 在这种情况下,在Groovy Postbuild中你可以写:

File script = new File("${manager.envVars['JENKINS_HOME']}/scripts/PostbuildActions.groovy")
Object actions = new GroovyClassLoader(getClass().getClassLoader()).parseClass(script).newInstance();

actions.setBuildName(manager, 'My Greatest Build');

If you wish to have the Groovy script in your Code Repository, and loaded onto the Build / Test Slave in the workspace, then you need to be aware that Groovy Postbuild runs on the Master. 如果您希望在代码存储库中安装Groovy脚本,并将其加载到工作区中的构建/测试从属服务器上,那么您需要注意Groovy Postbuild在主服务器上运行。

For us, the master is a Unix Server, while the Build/Test Slaves are Windows PCs on the local network. 对我们来说,主服务器是Unix服务器,而构建/测试从服务器是本地网络上的Windows PC。 As a result, prior to using the script, we must open a channel from the master to the Slave, and use a FilePath to the file. 因此,在使用脚本之前,我们必须打开从主服务器到从服务器的通道,并使用FilePath到该文件。

The following worked for us: 以下为我们工作:

// Get an Instance of the Build object, and from there
// the channel from the Master to the Workspace
build = Thread.currentThread().executable
channel = build.workspace.channel;

// Open a FilePath to the script
fp = new FilePath(channel, build.workspace.toString() + "<relative path to the script in Unix notation>")

// Some have suggested that the "Not NULL" check is redundant
// I've kept it for completeness
if(fp != null)
{
    // 'Evaluate' requires a string, so read the file contents to a String
    script = fp.readToString();
    // Execute the script
    evaluate(script);
} 

I've just faced with the same task and tried to use @Blaskovicz approach. 我刚刚面临同样的任务,并尝试使用@Blaskovicz方法。 Unfortunately it does not work for me, but I find upgraded code here (Zach Auclair) 不幸的是它对我不起作用,但我在这里找到升级的代码(Zach Auclair)

Publish here with minor changes: 在这里发布一些细微的变化:

postbuild task 后期任务

//imports
import hudson.model.*
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;

// define git file
def postBuildFile = manager.build.getEnvVars()["WORKSPACE"] + "/Jenkins/SimpleTaskPostBuildReporter.GROOVY"
def file = new File(postBuildFile)
// load custom class from file
Class groovy = this.class.classLoader.parseClass(file);
// create custom object
GroovyObject groovyObj = (GroovyObject) groovy.newInstance(manager);
// do report
groovyObj.report();

postbuild class file in git repo (SimpleTaskPostBuildReporter.GROOVY) git repo中的postbuild类文件(SimpleTaskPostBuildReporter.GROOVY)

class SimpleTaskPostBuildReporter {
  def manager

  public SimpleTaskPostBuildReporter(Object manager){
    if(manager == null) {
      throw new RuntimeException("Manager object can't be null")
    }
    this.manager = manager
  }

  public def report() {
    // do work with manager object
  }
}

I haven't tried this exactly. 我没有试过这个。

You could try the Jenkins Job DSL plugin which allows you to rebuild jobs from within jenkins using a Groovy DSL and supports post build groovy steps directly from the wiki 您可以尝试使用Jenkins Job DSL插件 ,它允许您使用Groovy DSL从jenkins内部重建作业,并直接从wiki支持构建时的groovy步骤

Groovy Postbuild Groovy Postbuild

Executes Groovy scripts after a build. 在构建之后执行Groovy脚本。

groovyPostBuild(String script, Behavior behavior = Behavior.DoNothing) Arguments: groovyPostBuild(String script,Behavior behavior = Behavior.DoNothing)参数:

script The Groovy script to execute after the build. script构建后要执行的Groovy脚本。 See the plugin's page for details on what can be done. 有关可执行操作的详细信息,请参阅插件页面。 behavior optional. 行为可选。 If the script fails, allows you to set mark the build as failed, unstable, or do nothing. 如果脚本失败,则允许您将构建标记为失败,不稳定或不执行任何操作。 The behavior argument uses an enum, which currently has three values: DoNothing, MarkUnstable, and MarkFailed. 行为参数使用枚举,当前有三个值:DoNothing,MarkUnstable和MarkFailed。

Examples: 例子:

This example will run a groovy script that prints hello, world and if that fails, it won't affect the build's status: 这个例子将运行一个打印hello,world的groovy脚本,如果失败,它将不会影响构建的状态:

 groovyPostBuild('println "hello, world"') This example will run a groovy script, and if that fails will mark the build as failed: groovyPostBuild('// some groovy script', Behavior.MarkFailed) This example will run a groovy script, and if that fails will mark the 

build as unstable: 建立不稳定:

 groovyPostBuild('// some groovy script', Behavior.MarkUnstable) (Since 1.19) 

There is a facility to use a template job (this is the bit I haven't tried) which could be the job itself so you only need to add the post build step. 有一个工具可以使用模板作业(这是我没有尝试过的),这可能是作业本身所以你只需要添加后期构建步骤。 If you don't use a template you need to recode the whole project. 如果您不使用模板,则需要重新编码整个项目。

My approach is to have a script to regenerate or create all jobs from scratch just so I don't have to apply the same upgrade multiple times. 我的方法是让脚本从头开始重新生成或创建所有作业,这样我就不必多次应用相同的升级。 Regenerated jobs keep their build history 重新生成的作业保留其构建历史记录

I was able to get the following to work (I also posted on this jira issue ). 我能够得到以下工作(我也发布了这个jira问题 )。

in my postbuild task 在我的postbuild任务中

this.class.classLoader.parseClass("/home/jenkins/GitlabPostbuildReporter.groovy")
GitlabPostbuildReporter.newInstance(manager).report()

in my file on disk at /home/jenkins/GitlabPostbuildReporter.groovy 在我的文件磁盘上/home/jenkins/GitlabPostbuildReporter.groovy

class GitlabPostbuildReporter {
  def manager
  public GitlabPostbuildReporter(manager){
    if(manager == null) {
      throw new RuntimeException("Manager object musn't be null")
    }
    this.manager = manager
  }
  public def report() {
    // do work with manager object
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Groovy Postbuild脚本Jenkins-杀死进程 - Groovy Postbuild Script Jenkins - Kill Process Jenkins访问文件在工作区中-Groovy PostBuild - Jenkins access file in workspace - groovy postbuild jenkins与groovy postbuild。无法在groovy脚本字段中执行任何操作 - jenkins with groovy postbuild .Not able to execute anything in groovy script field 为什么我的Groovy脚本在Jenkins脚本控制台中运行,而不是作为Groovy Postbuild脚本运行? - Why does my Groovy script run in the Jenkins Script Console but not as a Groovy Postbuild Script? 将Jenkins Groovy Postbuild步骤添加到所有作业 - Add Jenkins Groovy Postbuild step to all jobs 通过Groovy Postbuild优先考虑Jenkins Build - Prioritize Jenkins Build via Groovy Postbuild Groovy Postbuild 不在 Jenkins 上执行脚本 - Groovy Postbuild do not execute scripts on Jenkins 如何标记jenkins构建不稳定与groovy postbuild - How to mark the jenkins build unstable with groovy postbuild 如何在 Jenkins 中永久使用 Groovy PostBuild 更新全局环境变量并在其他后续构建中使用它? - How can I update a global Environment Variable using Groovy PostBuild in Jenkins permanently and use it in other subsequent builds? 是否可以在Jenkins groovy postbuild插件内部通过@grab使用外部jar? - Is it possible to use external jars via @grab from inside the Jenkins groovy postbuild plugin?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM