You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins共享库大量Shell脚本调用问题:无法定位groovy文件路径

解决Jenkins共享库批量调用互相依赖Shell脚本的问题

Jenkins共享库的resources目录资源是嵌入到类路径中的,无法直接通过文件系统路径访问,因此需要先将相关脚本批量复制到构建工作区,再执行目标脚本。

修改后的bar.groovy代码

def call() {
    script {
        withCredentials([sshUserPrivateKey(credentialsId: 'my-ssh', keyFileVariable: 'ssh_key', passphraseVariable: 'ssh_pass', usernameVariable: 'ssh_user')]) {
            // 在工作区创建临时目录存放脚本
            def scriptDir = "${env.WORKSPACE}/shared_scripts"
            sh "mkdir -p ${scriptDir}"
            
            // 批量复制resources下所有Shell脚本到临时目录,并添加执行权限
            findFiles(glob: '**/*.sh').each { file ->
                writeFile file: "${scriptDir}/${file.name}", text: libraryResource(file.path)
                sh "chmod +x ${scriptDir}/${file.name}"
            }
            
            // 执行目标脚本,此时同目录下的依赖脚本可被正常调用
            sh "${scriptDir}/script1.sh -u $ssh_user -i $ssh_key -b ${env.BUILD_ID}"
        }
    }
}

关键细节说明

  • libraryResource:用于读取共享库resources目录下的资源内容
  • writeFile:将读取到的资源内容写入构建工作区的本地文件
  • chmod +x:为脚本添加执行权限,保证脚本可正常运行
  • 批量复制后,脚本间的相对路径引用(如script1.sh中调用./script2.sh)会自动生效,因为它们处于同一目录

按需复制的替代写法

如果只需复制指定脚本,而非全部,可直接枚举脚本列表:

def call() {
    script {
        withCredentials([sshUserPrivateKey(credentialsId: 'my-ssh', keyFileVariable: 'ssh_key', passphraseVariable: 'ssh_pass', usernameVariable: 'ssh_user')]) {
            def scriptDir = "${env.WORKSPACE}/shared_scripts"
            sh "mkdir -p ${scriptDir}"
            
            // 复制指定的依赖脚本
            def targetScripts = ['script1.sh', 'script2.sh']
            targetScripts.each { scriptName ->
                writeFile file: "${scriptDir}/${scriptName}", text: libraryResource(scriptName)
                sh "chmod +x ${scriptDir}/${scriptName}"
            }
            
            sh "${scriptDir}/script1.sh -u $ssh_user -i $ssh_key -b ${env.BUILD_ID}"
        }
    }
}

内容的提问来源于stack exchange,提问作者jpgerdeman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 04:12:52