Monday, July 24, 2017

Oracle code - Jenkins check if file is present in workspace

When using Jenkins to automate parts of your build and deployment work in a CI/CD manner you do want to include certain failsafe manners. A common ask is to check if a certain file is present in your Jenkins workspace. In our example, we do pull code from a Gitlab repository to build a Maven based project. One of the first things we would like to ensure is that the pom.xml file is present. In case the pom.xml file is not present we know that the build will fail and we will never come to a position in which we can build the required .jar file for our project.

To check if a file is present you can use the below example

if (fileExists('pom.xml')) {
    echo 'Yes'
} else {
    echo 'No'
}

As you can see this is fairly straightforward check which will check if pom.xml is present. In case it is not present it will print "No", in case it is present it will print "Yes". In a realworld example you do want to take some action on this instead of printing that the file is not present, you could have the desire to abort the build. The below example could be used to do so

    currentBuild.result = 'ABORTED'
    error('pom.xml file has NOT been located')

The above example code will abort the Jenkins job and will give the error that the pom.xml file has not been found. The more complete example is shown below:

if (fileExists('pom.xml')) {
    echo 'Yes'
} else {
    currentBuild.result = 'ABORTED'
    error('pom.xml file has NOT been located')
}

Ensuring that you have checks like this in place will make the outcome of Jenkins more predictable and can safe you a lot of issues in a later stage. In reality, a large part of some of our code in Jenkins is often to make sure everything is in place and is doing what it is expected to do. Checking and error handling is a big part of automation. 

No comments: