Jenkins 凭证存了却找不到是怎么回事?

路杨 阅读 12

我在 Jenkins 里新建了一个 Username with password 类型的凭证,ID 填的是 my-git-cred,但 Pipeline 脚本里用 credentials(‘my-git-cred’) 就报错说找不到。

我确认过是在当前 Job 所在的文件夹下创建的凭证,不是全局的。Pipeline 代码大致是这样:

pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git credentialsId: 'my-git-cred', url: 'https://example.com/repo.git'
            }
        }
    }
}

控制台输出一直提示:Could not find credentials matching my-git-cred。是不是我放错位置了?还是 ID 写错了?

我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
♫广云
♫广云 Lv1
你这问题我太熟悉了,十次有九次是 credentials() 和 git 步骤混用导致的坑。

你写的这段 pipeline 里用了 git credentialsId: 'my-git-cred',但其实这是旧语法,和 credentials() 是两套机制,混用的话 Jenkins 根本不会去解析你传进去的 credentialsId,它会当成普通字符串去匹配——而你又没在全局凭据里配这个 ID,自然找不到。

正确写法是用 checkout 步骤 + credentialsId 放在 git 子配置里,或者用 withCredentials 包裹。推荐前者,干净点:

pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout([$class: 'GitSCM',
branches: [[name: '*/main']],
doGenerateSubmoduleConfigurations: false,
extensions: [],
userRemoteConfigs: [[
credentialsId: 'my-git-cred',
url: 'https://example.com/repo.git'
]]
])
}
}
}
}


或者更简洁的(如果你用的是新版本插件):

pipeline {
agent any
stages {
stage('Checkout') {
steps {
git branch: 'main',
url: 'https://example.com/repo.git',
credentialsId: 'my-git-cred'
}
}
}
}


注意:credentialsId 的值必须和你创建凭证时填的 ID 完全一致,大小写都别错。另外再确认下你建凭证的路径——如果是 Folder 下的 Job,凭证必须建在该 Folder 的凭据里(不是全局,也不是根目录)。路径不对也查不到,这个坑我踩过好几次。

最后说一句,别用 credentials('my-git-cred') 去包 git,它俩不搭,会失效。真要用 withCredentials,得这样:

withCredentials([usernamePassword(credentialsId: 'my-git-cred', 
usernameVariable: 'GIT_USER',
passwordVariable: 'GIT_PASS')]) {
sh 'git clone https://${GIT_USER}:${GIT_PASS}@example.com/repo.git .'
}


但没必要,直接上面那种写法就行,省事。
点赞 4
2026-02-25 18:27