Maroun
Maroun

Reputation: 95948

Running pure Groovy code in a step inside a Jenkinsfile

I have the following stages in my test.groocy pipeline:

stages {
  stage('Test') {
    steps {
       env.SOME_VAR = new File("settings.gradle")
         .readLines()
         .findAll { someLogic }
         .collect { it =~ /.*'(.*)'/ }
       echo "got: ${SOME_VAR}"
    }
  }
}

But I'm getting:

java.io.FileNotFoundException: settings.gradle (No such file or directory)

If I change the code to:

stages {
  stage('Test') {
    steps {
       sh(returnStdout: true,
       script: '''#!/bin/bash
                  cat settings.gradle''')
    }
  }
}

I can see the file's content.

  1. Why isn't it recognizing the file in the first snippet, but does recognize it in the second one?
  2. Is there a way to make the upper snippet works as expected in Jenkins?

Upvotes: 0

Views: 125

Answers (1)

daggett
daggett

Reputation: 28564

sh, as other Jenkins steps, started in current workspace directory.

So, you could replace native java/groovy new File with Jenkins readFile and the rest of your code should work.

readFile("settings.gradle").readLines()...

Or specify the full path for new File

new File("${WORKSPACE}/settings.gradle").readLines()...

Upvotes: 1

Related Questions