Skip to content

Commit b9c9979

Browse files
committed
更新 GitLab CI/CD 部分,調整私有 Registry 存取方法,新增使用 CI_JOB_TOKEN 和 Deploy Token 的建議
1 parent d86199e commit b9c9979

File tree

1 file changed

+31
-35
lines changed

1 file changed

+31
-35
lines changed

source/_posts/2025/gitlab-python-package-registry.md

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -148,51 +148,47 @@ EOF
148148
uv sync
149149
```
150150

151-
### 4. CI/CD 自動化發布
151+
### 4. CI/CD 中存取私有 Registry
152152

153-
設定 GitLab CI 自動構建並推送套件到 registry:
153+
專案在 GitLab CI/CD 中需要存取私有 Registry 時,有以下幾種方式:
154+
155+
#### 方法 1:使用 CI_JOB_TOKEN(推薦)
154156

155157
```yaml
156158
# .gitlab-ci.yml
157159
variables:
158-
REGISTRY_PATH: registry.gitlab.com/$GROUP_PATH/$PROJECT_NAME
160+
PIP_INDEX_URL: https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/api/v4/projects/${REGISTRY_PROJECT_ID}/packages/pypi/simple
161+
PIP_EXTRA_INDEX_URL: https://pypi.org/simple
159162

160-
stages:
161-
- build
162-
- publish
163+
build:
164+
stage: build
165+
script:
166+
- pip install -e .
167+
- # 其他構建步驟
168+
```
163169

164-
build-package:
170+
#### 方法 2:使用 Deploy Token
171+
172+
在 CI/CD 變數中設定 `GITLAB_DEPLOY_TOKEN`
173+
174+
```yaml
175+
build:
165176
stage: build
166177
script:
167-
# 構建 Python 套件
168-
- pip install build
169-
- python -m build
170-
artifacts:
171-
paths:
172-
- dist/
173-
174-
publish-to-registry:
175-
stage: publish
176-
dependencies:
177-
- build-package
178+
- export PIP_INDEX_URL="https://deploy-token-{TOKEN_ID}:${GITLAB_DEPLOY_TOKEN}@gitlab.com/api/v4/projects/${REGISTRY_PROJECT_ID}/packages/pypi/simple"
179+
- pip install -e .
180+
```
181+
182+
#### 方法 3:配合 uv 使用
183+
184+
```yaml
185+
build:
186+
stage: build
187+
before_script:
188+
- export GITLAB_TOKEN=${CI_JOB_TOKEN}
178189
script:
179-
# 設定認證
180-
- pip install twine
181-
- |
182-
cat > ~/.pypirc <<EOF
183-
[distutils]
184-
index-servers = gitlab
185-
186-
[gitlab]
187-
repository = https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}/packages/pypi
188-
username = gitlab-ci-token
189-
password = ${CI_JOB_TOKEN}
190-
EOF
191-
192-
# 上傳到 GitLab Package Registry
193-
- python -m twine upload --repository gitlab dist/*
194-
only:
195-
- main
190+
- uv sync
191+
- # 其他構建步驟
196192
```
197193

198194
### 6. Docker 映像支援多架構

0 commit comments

Comments
 (0)