I have to read some input from report.json file which is in the jenkins workspace. I am using the following code to read the file but it says file not found error. I am running this script on Groovy Postbuild step.
import hudson.model.*
def fileContents = new File('C:\\jenkinstest_slave\\workspace\\Cypress\\mochawesome-report\\report.json').readLines()
def result = fileContents.findAll { it.contains('passPercent') }
manager.listener.logger.println("matching word from findAll method= " +result)
Error:
Groovy script failed:
java.io.FileNotFoundException
Can someone please help me to resolve this?
Related
I am into a scenario where I need to read the console output and find a specific string and set this as environment variable. This variable I would be using in input to run a different script in same job.
for example: my jenkins job's console would contain something like
build_id: 123456
Can somebody help in finding this number and pass it to input.environment variable to other script in same job?
I have looked into this answer but its not working, I am getting groovy errors while running it in post build groovy script.
Jenkins pipeline, is there a way to set environment variable from console output
Script I am using:
import jenkins.model.*
jenkins = Jenkins.instance
def consoleLog = Jenkins.getInstance().getItemByFullName(env.JOB_NAME).getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER)).logFile.text
def buildId = (consoleLog =~ 'build_id="(.*)"')[0][1]
echo "build_id: $buildId"
env.build_id = buildId
Error I am getting:
ERROR: Failed to evaluate groovy script.
groovy.lang.MissingPropertyException: No such property: env for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
I am trying to run a groovy script in Jenkins slave node to retrieve child jobs from a folder in Jenkins slave node. Here is the groovy script I tried:
I tried some SO answers and found groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding
But this doesn't solve my problem.
Please find the code that I tried:
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import jenkins.model.*
static main(args){
def childJobFolder = "childJob"
def childJobNameList = []
def env = System.getenv()
// Setting the environment properties to variables.
def jenkinsUsername = env.UAT_JENKINS_MY_USER
def jenkinsPassword = env.UAT_JENKINS_MY_PASS
def jsonSlurper = new JsonSlurper()
// Getting the child job names from "childJob" folder
Jenkins.instance.getItemByFullName(childJobFolder).allJobs.each{
def childJobName = it.name.toString()
if(childJobName.startsWith("job-")){
childJobNameList.add(childJobName)
}
}
println "\n" + "Child Jobs Available: " + childJobNameList + "\n"
}
Here is what I got in the console:
Caught: groovy.lang.MissingPropertyException: No such property: Jenkins for class: hudson3067346520259876246
groovy.lang.MissingPropertyException: No such property: Jenkins for class: hudson3067346520259876246
at hudson3067346520259876246.run(hudson3067346520259876246.groovy:17)
Build step 'Execute Groovy script' marked build as failure
Can someone help me to fix this error? Thanks in advance!
Finally, I found out the solution for this error. This is caused by running on plain groovy script instead of system groovy script. As Jayan said the Jenkins variables only available for System groovy scripts and not for plain groovy script. For that reason I could not load Jenkins instances from plain groovy script.
I am calling a shared library groovy script from my Jenkins pipeline.
Using the pwd() method I can properly get the workspace path and I can even see the required file in the exact same location in the Jenkins node.
Still I am getting following error:
java.io.FileNotFoundException: C:\Jenkins\workspace\Demo\test\target\site\xyz\abc.csv (No such file or directory)
I have the groovy-scripts/vars/generateHtml.groovy shared library which is being called from the pipeline as generateHtml(). The relevant code snippet:
def call() {
def ws = pwd()
echo "path ${ws}: generateHtml>start"
def targetPath = "${ws}\\target\\"
def resultFile = targetPath + 'site\\xyz\\abc.csv'
def data = parseCsv(new File(resultFile).getText('UTF-8'))
...
Reading a file in Jenkins Pipelines goes via readFile. Don't use plain groovy for I/O.
I am preparing a Jenkins pipeline script in Groovy language. I would like to move all files and folders to another location. As Groovy supports Java so I used below java code to perform the operation.
pipeline{
agent any
stages{
stage('Organise Files'){
steps{
script{
File sourceFolder = new File("C:\\My-Source");
File destinationFolder = new File("C:\\My-Destination");
File[] listOfFiles = sourceFolder.listFiles();
echo "Files Total: " + listOfFiles.length;
for (File file : listOfFiles) {
if (file.isFile()) {
echo file.getName()
Files.copy(Paths.get(file.path), Paths.get("C:\\My-Destination"));
}
}
}
}
}
}
}
This code throws the bellow exception:
groovy.lang.MissingPropertyException: No such property: Files for
class: WorkflowScript
I tried with below code too, but it's not working either.
FileUtils.copyFile(file.path, "C:\\My-Destination");
Finally, I did try with java I/O Stream to perform the operation and the code is bellow:
def srcStream = new File("C:\\My-Source\\**\\*").newDataInputStream()
def dstStream = new File("C:\\My-Destination").newDataOutputStream()
dstStream << srcStream
srcStream.close()
dstStream.close()
But it's not working either and throws the below exception:
java.io.FileNotFoundException: C:\My-Source (Access is denied)
Can anyone suggest me how to solve the problem and please also let me know how can I delete the files from the source location after copy or move it? One more thing, during the copy can I filter some folder and files using wildcard? Please also let me know that.
Don't execute these I/O functions using plain Java/Groovy. Even if you get this running, this will always be executed on the master and not the build agents. Use pipeline steps also for this, for example:
bat("xcopy C:\\My-Source C:\\My-Destination /O /X /E /H /K")
or using the File Operations Plugin
fileOperations([fileCopyOperation(
excludes: '',
flattenFiles: false,
includes: 'C:\\My-Source\\**',
targetLocation: "C:\\My-Destination"
)]).
I assume I didn't hit the very right syntax for Windows paths here in my examples, but I hope you get the point.
I am trying to read the server name from the xml file in a pipeline script.
My Code:
node {
def str = "<root><HTTPTargetConnection><Loadbalancer><server name=\"myserver\" /> </Loadbalancer></HTTPTargetConnection></root>";
def rootNode = new XmlParser().parseText(str);
echo rootNode.HTTPTargetConnection.Loadbalancer.server.#name.value[0];
}
Exception:
[Pipeline] End of Pipeline
*
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:
unclassified field groovy.util.Node HTTPTargetConnection at
org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:367)
at
org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:363)
at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
Please help me in resolving this issue.
You're running into sandbox issues. The field in question is not authorized for use and therefore must be approved (in the script approval page).