GitLab API 自动化
GitLab 提供 REST API,运维常用场景包括:列出项目、查询 Pipeline 状态、手动触发 CI/CD、批量给项目加变量。推荐用 python-gitlab 封装,比裸 HTTP 更易维护。
环境准备
cd ~/python-for-ops
uv add python-gitlab
在 GitLab User Settings → Access Tokens 创建 Token,权限至少包含 api 或 read_api + write_repository(视操作而定)。
export GITLAB_URL="https://gitlab.example.com"
export GITLAB_TOKEN="glpat-xxxxxxxxxxxxxxxxxxxx" # 占位符,勿提交仓库
连接与列出项目
#!/usr/bin/env python3
"""列出 GitLab 组内项目,并按最后活动时间排序。"""
import os
import gitlab
def main() -> None:
url = os.environ["GITLAB_URL"]
token = os.environ["GITLAB_TOKEN"]
# 关闭 SSL 校验仅用于内网自签证书,生产环境应配置正确 CA
gl = gitlab.Gitlab(url, private_token=token, ssl_verify=True)
gl.auth() # 验证 Token 是否有效
group_path = "ops/platform" # 组路径,按实际修改
group = gl.groups.get(group_path)
# 按名称过滤,仅取前 20 个
projects = group.projects.list(search="app", order_by="last_activity_at", per_page=20)
for p in projects:
print(f"{p.path_with_namespace:40s} last_activity={p.last_activity_at}")
if __name__ == "__main__":
main()
查询与触发 Pipeline
#!/usr/bin/env python3
"""查询最近 Pipeline,并在需要时触发 deploy 分支构建。"""
import os
import gitlab
def list_recent_pipelines(gl: gitlab.Gitlab, project_id: int, ref: str = "main") -> None:
project = gl.projects.get(project_id)
pipelines = project.pipelines.list(ref=ref, per_page=5)
for pipe in pipelines:
# status: success / failed / running / pending ...
print(f"#{pipe.id} {pipe.status:10s} {pipe.web_url}")
def trigger_pipeline(gl: gitlab.Gitlab, project_id: int, ref: str, variables: dict | None = None) -> None:
project = gl.projects.get(project_id)
data: dict = {"ref": ref}
if variables:
# GitLab 要求变量格式为 [{"key": "...", "value": "..."}]
data["variables"] = [{"key": k, "value": v} for k, v in variables.items()]
pipe = project.pipelines.create(data)
print(f"已触发 Pipeline #{pipe.id},状态: {pipe.status}")
def main() -> None:
gl = gitlab.Gitlab(os.environ["GITLAB_URL"], private_token=os.environ["GITLAB_TOKEN"])
gl.auth()
pid = 12345 # 替换为实际 project_id
list_recent_pipelines(gl, pid, ref="main")
# 手动触发示例:部署 staging
trigger_pipeline(
gl,
pid,
ref="main",
variables={"DEPLOY_ENV": "staging", "IMAGE_TAG": "v1.2.3"},
)
if __name__ == "__main__":
main()
批量管理 CI 变量(谨慎)
def upsert_ci_variable(gl: gitlab.Gitlab, project_id: int, key: str, value: str, masked: bool = True) -> None:
"""创建或更新项目级 CI/CD 变量。"""
project = gl.projects.get(project_id)
try:
var = project.variables.get(key)
var.value = value
var.masked = masked
var.save()
print(f"已更新变量 {key}")
except gitlab.exceptions.GitlabGetError:
project.variables.create({"key": key, "value": value, "masked": masked})
print(f"已创建变量 {key}")
注意
- Token 权限遵循最小原则;写操作脚本先在测试项目验证
- 触发 Pipeline 前确认
ref与变量不会误推生产 - 内网 GitLab 注意 API 限流,批量操作建议加
time.sleep
小结
| 操作 | 常用 API / 方法 |
|---|---|
| 列项目 | groups.get().projects.list() |
| 查 Pipeline | project.pipelines.list() |
| 触发构建 | project.pipelines.create({"ref": ...}) |
| CI 变量 | project.variables.create() / .get().save() |
下一章对接 Harbor 镜像仓库,实现镜像查询与清理。