Skip to content

Commit dc5ad5a

Browse files
feat: Use Trusted Publishers with GitLab CI/CD
* PyPI Trusted Publisher support now includes GitLab CI/CD, so use generated OIDC tokens to publish to TestPyPI or PyPI as needed in GitLab pipelines. - c.f. https://blog.pypi.org/posts/2024-04-17-expanding-trusted-publisher-support/
1 parent 28d1a53 commit dc5ad5a

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

{{cookiecutter.project_name}}/{% if cookiecutter.__ci=='gitlab' %}.gitlab-ci.yml{% endif %}

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ cache:
1717
image: python:3.8-buster
1818
before_script:
1919
# want to set up a virtualenv to cache
20-
- apt-get install -y --no-install-recommends git
20+
- apt-get install -y --no-install-recommends git jq
2121
- python -V
2222
- python -m venv .venv
2323
- source .venv/bin/activate
24-
- python -m pip install -U pip pipx
24+
- python -m pip install -U pip pipx id
2525
- python -m pipx ensurepath
2626
- python -m pip freeze
2727

@@ -152,7 +152,12 @@ make_wheels:
152152
- make_wheels
153153
{%- endif %}
154154
script:
155-
- pipx run twine upload --verbose dist/*whl dist/*gz
155+
# Retrieve the OIDC token from GitLab CI/CD and exchange it for a PyPI API token
156+
- oidc_token=$(python -m id PYPI)
157+
- response=$(curl -X POST "${OIDC_MINT_TOKEN_URL}" -d "{\"token\":\"${oidc_token}\"}")
158+
- api_token=$(jq --raw-output '.token' <<< "${response}")
159+
160+
- pipx run twine upload --password "${api_token}" --verbose dist/*whl dist/*gz
156161

157162
deploy_staging:
158163
extends: .deploy
@@ -162,7 +167,7 @@ deploy_staging:
162167
variables:
163168
TWINE_REPOSITORY: testpypi
164169
TWINE_USERNAME: __token__
165-
TWINE_PASSWORD: $TESTPYPI_TOKEN
170+
OIDC_MINT_TOKEN_URL: "https://test.pypi.org/_/oidc/mint-token"
166171

167172
deploy_production:
168173
extends: .deploy
@@ -171,4 +176,4 @@ deploy_production:
171176
variables:
172177
TWINE_REPOSITORY: pypi
173178
TWINE_USERNAME: __token__
174-
TWINE_PASSWORD: $PYPI_TOKEN
179+
OIDC_MINT_TOKEN_URL: "https://pypi.org/_/oidc/mint-token"

0 commit comments

Comments
 (0)