46

I want to add a Build step with the Groovy plugin to read a file and trigger a build fail depending on the content of the file.

How can I inject the workspace file path in the groovy plugin ?

myFileDirectory = // Get workspace filepath here ???
myFileName = "output.log"
myFile = new File(myFileDirectory + myFileName)

lastLine = myFile.readLines().get(myFile.readLines().size().toInteger() - 1)
if (lastLine ==~ /.Fatal Error.*/ ){
    println "Fatal error found"
    System.exit(1)
} else{
   println "nothing to see here"
}
3
  • Jenkins can fail itself based on e.g. test results. What exactly You want achieve? Maybe there's a plugin for it already. Instead of passing a filename You can implement file search.
    – Opal
    Apr 8, 2014 at 5:23
  • I have an external program (exe) that I'm calling to generate an executable, it also generate a log file. I want to look in that log file and fail the build if [Fatal Error] is found.
    – Sergio
    Apr 8, 2014 at 10:32
  • Well, ok. I guess this log has some name that can be easily recognized. If so, find this file for given path and check the content.
    – Opal
    Apr 8, 2014 at 10:57

7 Answers 7

89

I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.

Turns out it's very easy, there is a readfile step, and I should have rtfm:

env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
4
  • 3
    Can you iterate through the object, after reading it? I am unable to do.. And Jenkins isn't throwing an error at the same time.. tried od debugging silly stuff.. pheww!
    – OK999
    Apr 7, 2017 at 3:08
  • 2
    the output is a String so you can parse that and split on \n if you want to look at it line by line
    – Cal
    Aug 19, 2017 at 18:42
  • There is no need to call pwd as using relative paths work just fine. Example : readfile("./version.txt")
    – Yeikel
    Aug 22, 2019 at 14:34
  • 1
    I want to access/read all txt files (including sub dir of workspace as well) using groovy postbuild. How to do that? May 19, 2020 at 11:45
30

If you are trying to read a file from the workspace during a pipeline build step, there's a method for that:

readFile('name-of-file.groovy')

For reference, see https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#readfile-read-file-from-workspace.

1
  • actually the provided link tells about readFile() (I didn't find any readFileFrom Workspace() ) - but thanks anyway, because readFile() solved my problem!
    – Roman
    Jul 3, 2017 at 10:39
12

Based on your comments, you would be better off with Text-finder plugin.

It allows to search file(s), as well as console, for a regular expression and then set the build either unstable or failed if found.

As for the Groovy, you can use the following to access ${WORKSPACE} environment variable:
def workspace = manager.build.getEnvVars()["WORKSPACE"]

2
  • 12
    #groovyNoob here. where can manager.bulid.getEnvVars be imported? Nov 9, 2015 at 7:21
  • Note that in system Groovy script step you just do def workspace = build.getEnvVars()["WORKSPACE"]. The build variable should be availble without any imports. So then you can read a file like so: def svnVersion = new File(workspace, 'artifacts/svn-revision').text;
    – Nux
    Oct 14, 2019 at 13:05
6

May this help to someone if they have the same requirement.

This will read a file that contains the Jenkins Job name and run them iteratively from one single job.

Please change below code accordingly in your Jenkins.

pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
             script{
            git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '

##To read file from workspace which will contain the Jenkins Job Name ###
           
     def filePath = readFile "${WORKSPACE}/ Your File Location"                   

##To read file line by line ###
 
     def lines = filePath.readLines() 
      
##To iterate and run Jenkins Jobs one by one ####

                    for (line in lines) {                                            
                      build(job: "$line/branchName",
                        parameters:
                        [string(name: 'vertical', value: "${params.vert}"),
                        string(name: 'environment', value: "${params.env}"),
                        string(name: 'branch', value: "${params.branch}"),
                        string(name: 'project', value: "${params.project}")
                        ]
                    )
                        }  
                                       }
                    
         }
         }
      }
   }

1
  • hey, how to read two files(one from workspace and other file from console output which i saved in variable) line by line and compare the lines,if it matches then print if not matches then exit 1
    – sam
    Mar 24, 2020 at 19:25
5

Although this question is only related to finding directory path ($WORKSPACE) however I had a requirement to read the file from workspace and parse it into JSON object to read sonar issues ( ignore minor/notes issues )

Might help someone, this is how I did it- from readFile

jsonParse(readFile('xyz.json')) 

and jsonParse method-

@NonCPS
def jsonParse(text) {
        return new groovy.json.JsonSlurperClassic().parseText(text);
}

This will also require script approval in ManageJenkins-> In-process script approval

1
  • 2
    FWIW there is now a readJSON function available from Jenkins in addition to readFile. Jun 8, 2021 at 12:33
0

If you already have the Groovy (Postbuild) plugin installed, I think it's a valid desire to get this done with (generic) Groovy instead of installing a (specialized) plugin.

That said, you can get the workspace using manager.build.workspace.getRemote(). Don't forget to add File.separator between path and file name.

0

As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:

import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*    

try{
//get Jenkins instance
    def jenkins = Jenkins.instance
//get job Item
    def item = jenkins.getItemByFullName("The_JOB_NAME")
    println item
// get workspacePath for the job Item
    def workspacePath = jenkins.getWorkspaceFor (item)
    println workspacePath

    def file = new File(workspacePath.toString()+"\\pom.xml")
    def pomFile = new XmlSlurper().parse(file)
    def pomModules = pomFile.modules.children().join(",")
    return pomModules
} catch (Exception ex){
    println ex.message
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.