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

路杨 阅读 37

我在 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 写错了?

我来解答 赞 8 收藏
二维码
手机扫码查看
2 条解答
程序员予曦
遇到这种凭证找不到的问题,老Jenkins玩家都会先检查三个地方:

1. 凭证作用域对不对。你说是当前文件夹下的凭证,那要确认Pipeline Job确实在这个文件夹里。Jenkins的文件夹层级有时候会坑人,建议直接进Job配置页面,在URL里看路径。

2. ID大小写问题。Jenkins的credentialsId是严格区分大小写的,你创建时用my-git-cred,使用时也得完全一致。建议在凭证管理页面直接复制ID。

3. 凭证类型是否匹配。既然你用git步骤,确认下凭证类型选的是Username with password而不是SSH Key之类的。

可以试试这个debug方法:在Pipeline里加个withCredentials块测试下:

steps {
withCredentials([usernamePassword(credentialsId: 'my-git-cred', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
sh 'echo $USER'
}
}


如果这样能输出用户名,说明凭证是存在的,可能是git步骤参数写错了。另外,全局凭证和文件夹凭证混用时容易出问题,实在不行就删了重建个全局凭证试试。
点赞 1
2026-03-09 11:10
♫广云
♫广云 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 .'
}


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