如何在setup.cfg中配置GitLab私有Python依赖的索引URL及安全凭证?
我所在公司有自托管的GitLab实例,我在其中一个仓库维护了名为dep的Python包,已经完成对应的PyPI包仓库配置。生成了带read_api权限的令牌后,能通过以下命令成功安装该包:
python -m pip install dep --index-url https://__token__:<personal_access_token>@<gitlab_server_host>/api/v4/projects/<gitlab_project_id>/packages/pypi/simple
现在我在另一个仓库有main包,想把dep作为依赖:
- 直接在
setup.cfg的install_requires里声明dep,执行python -m pip install -e <path_to_main_package>时会因找不到版本失败(符合预期,因为没上传到公共PyPI) - 尝试用
dependency_links指定私有仓库地址,同样失败 - 用Git依赖的方式能成功安装,但会把令牌明文存在
setup.cfg里,提交代码有安全风险:
install_requires = <other_packages> dep @ git+https://__token__:<personal_access_token>@<gitlab_server_host>/<gitlab_group_id>/<gitlab_project_id>.git#egg=dep&subdirectory=<relative_path_from_repo_root> <few_more_packages>
核心问题:
- 如何在
setup.cfg中指定私有依赖的索引URL? - 如何通过环境变量或其他安全方式传递令牌?
另外需要方案支持CI环境和Dockerfile自动安装main包,能通过环境变量传凭证,无需手动输入。
1. 在setup.cfg中指定私有依赖的索引URL
setup.cfg本身不支持直接配置私有索引,可通过pip配置文件或安装时传递命令行参数解决,同时setup.cfg里正常声明依赖即可:
方式一:本地开发用pip配置文件
在用户目录下创建/修改~/.pip/pip.conf(Linux/macOS)或%APPDATA%\pip\pip.ini(Windows),添加私有仓库配置:
[global] index-url = https://pypi.org/simple extra-index-url = https://__token__:<personal_access_token>@<gitlab_server_host>/api/v4/projects/<gitlab_project_id>/packages/pypi/simple
setup.cfg只需正常声明依赖:
install_requires = <other_packages> dep <few_more_packages>
执行pip install -e .时,pip会自动从配置的私有索引查找dep。
方式二:通用场景用命令行参数
无需修改setup.cfg,安装main包时直接指定私有索引:
python -m pip install -e <path_to_main_package> --extra-index-url https://__token__:<personal_access_token>@<gitlab_server_host>/api/v4/projects/<gitlab_project_id>/packages/pypi/simple
这种方式适配CI、Docker等临时指定索引的场景。
2. 通过环境变量安全传递令牌
不管用pip配置文件还是命令行参数,都可以用环境变量替换明文令牌,避免硬编码:
本地/CI环境:直接引用环境变量
先设置环境变量,再执行安装:
export GITLAB_PYPI_TOKEN="你的个人访问令牌" python -m pip install -e . --extra-index-url https://__token__:$GITLAB_PYPI_TOKEN@<gitlab_server_host>/api/v4/projects/<gitlab_project_id>/packages/pypi/simple
Dockerfile中传递令牌
用ARG和ENV结合构建参数传递令牌:
FROM python:3.11-slim # 声明构建参数(令牌) ARG GITLAB_PYPI_TOKEN # 生成pip配置文件,引用环境变量 RUN echo "[global]\nextra-index-url = https://__token__:${GITLAB_PYPI_TOKEN}@<gitlab_server_host>/api/v4/projects/<gitlab_project_id>/packages/pypi/simple" > /etc/pip.conf # 复制并安装main包 COPY . /app WORKDIR /app RUN pip install -e .
构建镜像时传递令牌:
docker build --build-arg GITLAB_PYPI_TOKEN="你的个人访问令牌" -t main-package .
GitLab CI环境配置
在GitLab项目的Settings > CI/CD > Variables中添加GITLAB_PYPI_TOKEN变量(勾选"Mask variable"防止日志泄露),然后在.gitlab-ci.yml中使用:
install-main: stage: build script: - pip install -e . --extra-index-url https://__token__:$GITLAB_PYPI_TOKEN@<gitlab_server_host>/api/v4/projects/<gitlab_project_id>/packages/pypi/simple
补充说明
dependency_links在pip 19.0+版本已被废弃,官方推荐用--extra-index-url或pip配置文件管理私有仓库依赖,这也是你之前尝试dependency_links失败的原因。
内容的提问来源于stack exchange,提问作者yarnabrina

