I have a shared jenkins library, that contains a large number of shell scripts. These shell scripts source each other.
I know I can copy individual files using libraryResource
. Since I’d be copying a lot of files I’d prefer to call the scripts where they are.
My directory structure
+
|- resource
|-script1.sh
|-script2.sh
|- var
|-bar.groovy (calls script1.sh, which needs script2.sh)
bar.groovy
looks like this
def call(){
script {
withCredentials([sshUserPrivateKey(credentialsId: 'my-ssh', keyFileVariable: 'ssh_key', passphraseVariable: 'ssh_pass', usernameVariable: 'ssh_user')]) {
scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
sh "sh ${scriptDir}/../resources/script1.sh -u $ssh_user -i $ssh_key -b ${env.BUILD_ID}"
}
}
}
my jenkinsfile looks something like this
@Library('mylib')
pipeline {
stages {
stage("calling script") {
steps {
bar()
}
}
}
}
I tried variations, but I cannot get the location of bar.groovy
new File(getClass().protectionDomain.codeSource.location.path)
// /opt/jenkins/plugins/workflow-cps/WEB-INF/lib/workflow-cps.jar
new File(".")
// /opt/jenkins/.
__FILE__
// not defined (found in the Job-DSL documentation)
I know getClass
returns the Java Instance, but I can’t find any useful property there.
Found the answer here /a/50475957
import groovy.transform.SourceURI
def call(){
script {
@SourceURI
URI sourceUri
withCredentials([sshUserPrivateKey(credentialsId: 'my-ssh', keyFileVariable: 'ssh_key', passphraseVariable: 'ssh_pass', usernameVariable: 'ssh_user')]) {
scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
sh "sh ${scriptDir}/../resources/script1.sh -u $ssh_user -i $ssh_key -b ${env.BUILD_ID}"
}
}
}