我有一个共享的jenkins库,其中包含大量的shell脚本。这些 shell 脚本相互来源。
libraryResource
复制单个文件。由于我要复制很多文件,所以我更愿意在脚本所在的位置调用它们。
我的目录结构
+
|- resource
|-script1.sh
|-script2.sh
|- var
|-bar.groovy (calls script1.sh, which needs script2.sh)
bar.groovy
看起来像这样
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}"
}
}
}
我的詹金斯文件看起来像这样
@Library('mylib')
pipeline {
stages {
stage("calling script") {
steps {
bar()
}
}
}
}
我尝试了各种变体,但无法获取
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)
我知道
getClass
返回Java实例,但我在那里找不到任何有用的属性。
在这里找到答案https://stackoverflow.com/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}"
}
}
}