我的任务是收集节点详细信息并以详细格式列出。我需要将数据写入文件并将其保存为csv文件,并将其附加为工件。但是我无法使用插件“ Execute System Groovy”作为构建步骤,在詹金斯中使用groovy脚本创建文件
import jenkins.model.Jenkins import hudson.model.User import hudson.security.Permission import hudson.EnvVars EnvVars envVars = build.getEnvironment(listener); filename = envVars.get('WORKSPACE') + "\\node_details.txt"; //filename = "${manager.build.workspace.remote}" + "\\node_details.txt" targetFile = new File(filename); println "attempting to create file: $targetFile" if (targetFile.createNewFile()) { println "Successfully created file $targetFile" } else { println "Failed to create file $targetFile" } print "Deleting ${targetFile.getAbsolutePath()} : " println targetFile.delete()
获得的输出
attempting to create file: /home/jenkins/server-name/workspace/GET_NODE_DETAILS\node_details.txt FATAL: No such file or directory java.io.IOException: No such file or directory at java.io.UnixFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:947) at java_io_File$createNewFile.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112) at Script1.run(Script1.groovy:13) at groovy.lang.GroovyShell.evaluate(GroovyShell.java:682) at groovy.lang.GroovyShell.evaluate(GroovyShell.java:666) at hudson.plugins.groovy.SystemGroovy.perform(SystemGroovy.java:81) at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20) at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:772) at hudson.model.Build$BuildExecution.build(Build.java:199) at hudson.model.Build$BuildExecution.doRun(Build.java:160) at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:535) at hudson.model.Run.execute(Run.java:1732) at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43) at hudson.model.ResourceController.execute(ResourceController.java:88) at hudson.model.Executor.run(Executor.java:234)
有时我看到人们使用“管理器”对象,我该如何访问它?关于如何完成任务有任何想法吗?
问题 Groovy系统脚本始终在jenkins主节点中运行,而工作区是jenkins从节点中的文件路径,而该路径在主节点中不存在。
您可以通过代码验证
theDir = new File(envVars.get('WORKSPACE')) println theDir.exists()
它将返回 false
false
如果不使用从节点,它将返回 true
true
解决方案 由于我们不能使用normal File,因此必须使用FilePath http://javadoc.jenkins- ci.org/hudson/FilePath.html
File
FilePath
if(build.workspace.isRemote()) { channel = build.workspace.channel; fp = new FilePath(channel, build.workspace.toString() + "/node_details.txt") } else { fp = new FilePath(new File(build.workspace.toString() + "/node_details.txt")) } if(fp != null) { fp.write("test data", null); //writing to file }
然后它在两种情况下都有效。