GitLab 使用 Personal Access Token(PAT) 作为账号密码的安全替代,用于 REST API 调用和 HTTPS Git 操作。

创建 Token

Settings → Access tokens → Add new token,选择到期时间和 Scope 后生成,只在创建时显示一次,需立即保存。

Token 前缀格式:glpat-xxxx(Personal Access Token),区别于 Runner 注册用的 glrt-xxxx。

1. 调用 REST API

将 token 放入请求头 PRIVATE-TOKEN:

export GITLAB_TOKEN="glpat-xxxx"
 
# 列出项目
curl -H "PRIVATE-TOKEN: $GITLAB_TOKEN" https://gitlab.com/api/v4/projects
 
# 创建 MR
curl -X POST \
  -H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"source_branch":"feature","target_branch":"main","title":"My MR"}' \
  https://gitlab.com/api/v4/projects/123/merge_requests
 
# 打 tag
curl -X POST \
  -H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
  -d "tag_name=v1.0.0&ref=main" \
  https://gitlab.com/api/v4/projects/123/repository/tags
 
# 触发 Pipeline
curl -X POST \
  -H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
  https://gitlab.com/api/v4/projects/123/pipeline?ref=main

API 基础 URL:https://gitlab.com/api/v4(自托管实例替换 domain)。

2. HTTPS Git 操作(clone/push/pull)

将 token 嵌入 URL 作为 HTTP 密码:

export GITLAB_TOKEN="glpat-xxxx"
 
# clone
git clone https://oauth2:${GITLAB_TOKEN}@gitlab.com/group/repo.git
 
# 已有仓库设置 remote
git remote set-url origin https://oauth2:${GITLAB_TOKEN}@gitlab.com/group/repo.git
 
# push(之后正常 push 即可)
git push origin main

不要把含 token 的 URL 硬编码进 Dockerfile 或提交到仓库;CI 场景优先用 CI_JOB_TOKEN 代替。

3. 在 CI/CD Pipeline 中使用

在 Settings → CI/CD → Variables 中以 masked 变量存入,Job 脚本读取:

deploy:
  script:
    - curl -H "PRIVATE-TOKEN: $GITLAB_TOKEN" $CI_API_V4_URL/projects/$CI_PROJECT_ID/...

内置的 CI_JOB_TOKEN 也能访问同 group 下的 API(权限更窄,推荐在 CI 内优先使用)。

权限范围(Scope)

创建 token 时按最小权限原则勾选:

Scope能力
api完整 REST API 访问(含读写所有资源)
read_api只读 REST API
read_user读取当前用户信息
read_repository读取仓库代码(git clone / fetch)
write_repository读写仓库代码(git push)
read_registry读取 Container Registry 镜像
write_registry推送镜像到 Container Registry
create_runner创建 Runner(Runner 注册场景)
manage_runner管理 Runner(暂停/删除等)
k8s_proxy通过 GitLab 代理访问 Kubernetes 集群

常用组合:

  • 脚本/自动化工具只调 API → api
  • 只拉取代码 → read_repository
  • CI 镜像构建推送 → read_registry + write_registry
  • 全功能(API + Git 读写)→ api + write_repository

Token 类型对比

类型前缀用途
Personal Access Tokenglpat-个人账号授权,API 与 Git 操作
Project Access Tokenglpat-作用域限于单个项目
Group Access Tokenglpat-作用域限于 Group 及其子项目
CI Job Token无前缀CI Job 内自动注入,短期有效
Runner Auth Tokenglrt-Runner 注册/认证用,见 cicd-runner

相关