Course contentsShow
← Python
Lesson 1042 of 1,06016. Capstone and AutomationFree lesson

Automating Package Releases to PyPI

Configure CI/CD pipelines to automatically build and publish new package versions to PyPI upon creating a formal release tag.

Automating Package Releases to PyPI

In this lesson, you will learn how to trigger an automated workflow that builds and publishes your Python package to PyPI the moment you create a formal release tag in your repository.

Up until now, you have manually executed poetry build and poetry publish to distribute your code. While manual distribution is fine for experimentation, it is prone to human error—such as forgetting to increment the version number or accidentally pushing an untested build. By leveraging CI/CD (specifically GitHub Actions), you can delegate this entire process to a secure, repeatable pipeline.

Triggering on Tags

The core idea is to configure a workflow file (e.g., .github/workflows/release.yml) that listens specifically for push events involving tags. By using the on.push.tags filter, your pipeline remains dormant during daily development and only activates when you intentionally mark a release.

on:
  push:
    tags:
      - 'v*'  # Triggers only when a tag starting with 'v' is pushed

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install Poetry
        run: pipx install poetry
      - name: Build and Publish
        run: |
          poetry build
          poetry publish --username __token__ --password ${{ secrets.PYPI_TOKEN }}

Ensuring Security and Integrity

Because this process runs in an ephemeral environment, you must handle your credentials with care. As discussed in our previous modules on "Managing Secrets," you should never hardcode your PyPI API tokens in your repository. Instead, store your PYPI_TOKEN in the repository’s "Secrets" settings. During the workflow execution, the runner injects this secret as an environment variable, ensuring that only authenticated builds can modify your project on PyPI.

By pinning your dependencies and using your lockfiles, you ensure that the version of your code being published is identical to the one you tested locally. Once the CI pipeline confirms the build succeeds, the automated process handles the upload, effectively closing the loop from "code change" to "public distribution."

Key Takeaway: Automating your PyPI release via CI/CD tags guarantees that every published version is consistent, verified, and deployed without manual intervention.