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

如何在Jenkinsfile中提取Bitbucket仓库的repositorySlug和projectKey并打印输出

提取Bitbucket仓库的projectKey和repositorySlug并打印

我来帮你搞定这个问题!当你在Jenkins Pipeline中用checkout scm拉取Bitbucket仓库代码时,Jenkins会自动把当前配置的SCM实例存在scm变量里。针对Bitbucket仓库(不管是Server还是Cloud),我们可以直接从这个对象里提取projectKey和repositorySlug,不用额外调用API。

完整的Jenkinsfile示例(声明式流水线)

pipeline {
    agent any

    stages {
        stage('拉取代码并提取仓库信息') {
            steps {
                // 拉取关联仓库的最新提交
                checkout scm

                // 提取并打印Bitbucket仓库信息
                script {
                    // 将通用SCM对象转换为Bitbucket专属类型(需提前安装Bitbucket相关插件)
                    def bitbucketRepo = scm as BitbucketSCM
                    
                    // 提取关键变量
                    def projectKey = bitbucketRepo.getProjectKey()
                    def repositorySlug = bitbucketRepo.getRepositorySlug()

                    // 输出到控制台
                    echo "✅ 提取到Bitbucket仓库信息:"
                    echo "Project Key: *${projectKey}*"
                    echo "Repository Slug: *${repositorySlug}*"
                }
            }
        }
    }
}

关键细节说明

  1. 插件依赖:确保你的Jenkins已经安装了Bitbucket Server Plugin(Bitbucket Cloud也兼容这个插件,两者的SCM类型都是BitbucketSCM)。
  2. 类型转换:scm是通用的SCM父类,转成BitbucketSCM才能调用Bitbucket特有的方法。
  3. Groovy简化写法:Groovy支持直接访问属性(不用写getXXX()),也可以这么写:
    def projectKey = bitbucketRepo.projectKey
    def repositorySlug = bitbucketRepo.repositorySlug
    

脚本式流水线版本

如果用的是脚本式流水线,写法会更简洁:

node {
    // 拉取代码
    checkout scm

    // 提取仓库信息
    def bitbucketRepo = scm as BitbucketSCM
    def projectKey = bitbucketRepo.projectKey
    def repoSlug = bitbucketRepo.repositorySlug

    // 打印输出
    echo "Bitbucket Project Key: ${projectKey}"
    echo "Bitbucket Repository Slug: ${repoSlug}"
}

容错处理(可选)

为了避免SCM类型不匹配报错,可以加个类型检查:

script {
    if (scm instanceof BitbucketSCM) {
        def projectKey = scm.projectKey
        def repoSlug = scm.repositorySlug
        echo "提取成功:Project Key = ${projectKey}, Repo Slug = ${repoSlug}"
    } else {
        echo "⚠️ 当前配置的SCM不是Bitbucket类型,请检查Jenkins项目的源码管理设置"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:55:30