How to run shell script file within the jenkins shared libary

292 Views Asked by At

I'd like to execute a shell file from within the shared library itself.

here is the path of the file:

libraryFoo/resources/foo.sh

my PipelineUtils package path within the library: libraryFoo/src/f1.org.pipeline/PipelineUtils

class PipelineUtils implements Serializable {
   ...
   def shell() {
    pipeline.sh(
            script: resources/foo.sh,
            returnStdout: true
    )
  }
}

and it is implemented in the pipeline:

@Library('libraryFoo') _
import f1.org.pipeline.PipelineUtils

...

    stage('Tag SCM') {
        def utils = new PipelineUtils()
        utils.shell()
    }
1

There are 1 best solutions below

0
Noam Helmer On

In order to read files from the resources folder of your shared library you will need to use a designated step created exactly for this called libraryResource:

libraryResource: Load a resource file from a shared library
Reads a resource from a shared library and returns its content as a plain string.

  • resource
    Relative (/-separated) path to a resource in a shared library's /resources folder.
  • encoding (optional) The encoding to use when reading the resource. If left blank, the platform default encoding will be used. Binary files can be read into a Base64-encoded string by specifying "Base64" as the encoding.

So in your case you can use it to load the script and run it using the sh step, assuming pipeline is your object that holds the script context it will look like:

class PipelineUtils implements Serializable {
   ...
def shell() {
   pipeline.sh(
      // Load the script as string and run using sh step
      script: pipeline.libraryResource('foo.sh'),
              returnStdout: true
   )
}

Alternatively you can also load the script and rewrite it to a local file if you need it for future use:

class PipelineUtils implements Serializable {
   ...
def shell() {
   // Load  the file from resources folder and recreate it locally
   def fileContent = pipeline.libraryResource('foo.sh')
   pipeline.writeFile(file: 'localFile.sh`, text: fileContent)

   pipeline.sh(
       // Use the file from the file System
       ...
   )
}