GitLab CI/CD流水线克隆仓库失败:2FA启用后的认证问题
GitLab CI/CD仓库克隆认证失败解决方案
问题背景
账号已启用2FA,配置了简单的.gitlab-ci.yml:
stages: - build build-job: stage: build script: - echo "Compiling the code..." - echo "Compile complete."
通过Docker在Windows本地部署GitLab Runner,注册及启动命令:
docker run --rm -v C:\GitLab-Runner\config:/etc/gitlab-runner gitlab/gitlab-runner register --non-interactive --url "https://gitlab.example.com/" --token "xxxxxxxxx" --executor "docker" --docker-image alpine:latest --description "docker-runner" docker run -d --name gitlab-runner --restart always -v C:\GitLab-Runner\config:/etc/gitlab-runner -v /var/run/docker.sock:/var/run/docker.sock gitlab/gitlab-runner:latest
作业执行时出现认证失败错误:
Running with gitlab-runner 16.7.0 (102c81ba) on docker-runner ecYGetzCE, system ID: r_liw1BfjncGQC Preparing the "docker" executor 00:04 Using Docker executor with image alpine:latest ... Pulling docker image alpine:latest ... Using docker image sha256:f8c20f8bbcb684055b4fea470fdd169c86e87786940b3262335b12ec3adef418 for alpine:latest with digest alpine@sha256:51b67269f354137895d43f3b3d810bfacd3945438e94dc5ac55fdac340352f48 ... Preparing environment 00:01 Running on runner-ecygetzce-project-5-concurrent-0 via 90e92b7f12d5... Getting source from Git repository 00:01 Fetching changes with git depth set to 20... Reinitialized existing Git repository in /builds/x/apxxx/xxxx/.git/ remote: HTTP Basic: Access denied. The provided password or token is incorrect or your account has 2FA enabled and you must use a personal access token instead of a password. See http://gitlab.example.com/help/topics/git/troubleshooting_git#error-on-git-fetch-http-basic-access-denied fatal: Authentication failed for 'http://gitlab.example.com/xxx/xxxx.git/' Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1
错误原因
账号启用2FA后,GitLab不再允许使用账号密码进行仓库的HTTP认证,必须使用**个人访问令牌(PAT)**替代密码完成克隆操作。
解决方法
方法1:生成个人访问令牌(PAT)并配置到Runner
- 登录GitLab账号,进入用户设置 > 访问令牌
- 填写令牌名称,勾选
read_repository权限(如需推送代码可额外勾选write_repository),设置过期时间后生成令牌,务必保存好生成的令牌内容。 - 找到Runner配置文件
C:\GitLab-Runner\config\config.toml,在[[runners]]区块内添加Git认证配置:
[runners.git] clone_url = "https://gitlab.example.com/" [runners.git.authentication] username = "你的GitLab用户名" password = "刚才生成的个人访问令牌"
- 重启GitLab Runner容器使配置生效:
docker restart gitlab-runner
方法2:在项目CI/CD变量中设置认证令牌
- 生成个人访问令牌(步骤同方法1)
- 进入项目的Settings > CI/CD > Variables,添加变量
CI_GIT_TOKEN,值为生成的PAT,可勾选Protect variable和Mask variable提升安全性。 - 重新触发CI作业,GitLab会自动使用该令牌完成仓库克隆认证。
额外检查
确保Runner注册时使用的--token是项目的Runner注册令牌(可在项目的Settings > CI/CD > Runners中获取),而非用户个人令牌。
内容的提问来源于stack exchange,提问作者Pratik Sharma
相关产品推荐
相关产品推荐

