Skip to content

Using a Gitlab pipeline for building and publishing a python package

Steps

1. Prepare Your Python Package

Ensure your Python package is properly structured and includes the following:

A pyproject.toml file for package configuration.

A README.md file for documentation.

2. Create a .gitlab-ci.yml File

This file defines the pipeline stages and jobs. Below is an example .gitlab-ci.yml for building and publishing a Python package:

Bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
default:
  image: python:3.13
  cache:
    paths:
      - .pip-cache/
  before_script:
    - python --version
    - pip install --upgrade pip
    - pip install build twine

stages:
  - build
  - publish

variables:
  PIP_CACHE_DIR: "$CI_PROJECT_DIR/.pip-cache"

build:
  stage: build
  script:
    - python -m build
  artifacts:
    paths:
      - dist/


publish:
  stage: publish
  script:
    - TWINE_PASSWORD=${CI_JOB_TOKEN} TWINE_USERNAME=gitlab-ci-token python -m twine upload --repository-url ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi dist/*
  rules:
    - if: $CI_COMMIT_TAG

3.Push Your Code and Tags

Push your code to the GitLab repository. To trigger the publish stage, create and push a tag