8

I have a Shared Library with a .groovy script that I call in a jenkinsfile like this:

MySharedLibFunction{ .. some args}

I also have a .ps1 file in my shared library I want to execute. But if I do powershell pwd from in my shared library function when I call that function from my jenkinsfile the current working directory is the jenkins working directory of my pipeline where the jenkinsfile is located (which is usually what you want).

Is there a way to access files in the shared lib? I want to do powershell -File ps1FileInMySharedLibVarsFolder.ps1

14

You can only get the contents using the built-in step libraryResource. That's why have the following functions in my shared library to copy it to a temporary directory and return the path to the file:

/**
  * Generates a path to a temporary file location, ending with {@code path} parameter.
  * 
  * @param path path suffix
  * @return path to file inside a temp directory
  */
@NonCPS
String createTempLocation(String path) {
  String tmpDir = pwd tmp: true
  return tmpDir + File.separator + new File(path).getName()
}

/**
  * Returns the path to a temp location of a script from the global library (resources/ subdirectory)
  *
  * @param srcPath path within the resources/ subdirectory of this repo
  * @param destPath destination path (optional)
  * @return path to local file
  */
String copyGlobalLibraryScript(String srcPath, String destPath = null) {
  destPath = destPath ?: createTempLocation(srcPath)
  writeFile file: destPath, text: libraryResource(srcPath)
  echo "copyGlobalLibraryScript: copied ${srcPath} to ${destPath}"
  return destPath
}

As it returns the path to the temp file, you can pass this to any step expecting a file name:

sh(copyGlobalLibraryScript('test.sh'))

for a file residing in resources/test.sh within your shared library.

|improve this answer|||||
  • I also endet up with a solution like this. But it seems quite clumsy to me - I'd prefer something like an option to automatically copy the library (or at least it's 'resource' folder) into workspace... – Roman Jan 30 '18 at 15:45
  • Useful but how can we load files from shared library that are inside a folder under resources BUT we don't know neither the number of files neither the files names inside that folder . – codeGeass Jul 4 '18 at 9:15
  • @Roman How did you import just the resources folder into workspace ? – codeGeass Jul 4 '18 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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