7

As you know, in Shared libraries in Jenkins, it is possible to load a resource (located in resources folder) by doing:

libraryResource("script.sh")

Now my use case is that I want to load number of files inside a folder under resources :

+ resources
 + teamA
  + script1.sh
  + script2.sh

And I want to load all those files before doing anything : I did a method in the shared library:

new File(scriptsFolder).eachFile() { file->

 writeFile([file:"${env.workspace}/${file.getName()}",text:libraryResource("$scriptsFolder/${file.getName()}")])
 sh("chmod +x ${env.workspace}/${file.getName()}")
}

where scriptsFolder= "teamA"

Of cource I'm getting java.io.IOException: Is a directory Because libraryResource must get a file path parameter.

So is, there a way to load all those files without knowing their names or their number?

mkobit
  • 43,979
  • 12
  • 156
  • 150
sirineBEJI
  • 1,170
  • 2
  • 14
  • 25

2 Answers2

12

You can get absolute path of your shared library using Groovy @SourceURI annotation:

// vars/get_resource_dir.groovy
import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths

class ScriptSourceUri {
    @SourceURI
    static URI uri
}

def call() {
    Path scriptLocation = Paths.get(ScriptSourceUri.uri)
    return scriptLocation.getParent().getParent().resolve('resources').toString()
}

Using the path you can invoke your scripts as usual:

sh "${get_resource_dir()}/com/example/test.sh"
  • This looked like the ideal solution to my problem... Except that this triggers two security exceptions: 1) "Scripts not permitted to use staticMethod java.net.URI create java.lang.String." 2) "Scripts not permitted to use staticMethod java.nio.file.Paths get java.net.URI." And the second is red-flagged by Jenkins as "Approving this signature may introduce a security vulnerability! You are advised to deny it." I can't take that risk :-( – Jean-François Larvoire Feb 07 '22 at 17:07
0

I decided to use the power of shell scripting. Jenkins server and slaves are all on Linux.

given: I am in a sub-directory, and the resources folder is one directory up.

String folder = "resources/teamA"
sh(script: "cp -R ../${folder}/. .")

// Verify files
def status = steps.sh(script: "diff ../${folder}/ .", returnStatus : true)

if(status.equals(0)) {
    // do that thing you do
} else {
    error "FAILURE not all files required exist"
}