Skip to content
Latchkey

How to Cache a Poetry Virtualenv in GitHub Actions

Force the venv into the project with virtualenvs.in-project, then cache .venv keyed on poetry.lock.

Poetry resolves and installs into a virtualenv. Pin that venv into the repo with poetry config virtualenvs.in-project true, then cache .venv keyed on poetry.lock so a clean run restores a ready-to-use environment.

Steps

  • Run poetry config virtualenvs.in-project true so the venv lives at .venv.
  • Cache .venv keyed on hashFiles('**/poetry.lock').
  • Run poetry install --no-interaction.

Workflow

.github/workflows/ci.yml
steps:
  - uses: actions/checkout@v4
  - uses: actions/setup-python@v5
    with:
      python-version: '3.12'
  - run: pipx install poetry && poetry config virtualenvs.in-project true
  - uses: actions/cache@v4
    with:
      path: .venv
      key: poetry-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
      restore-keys: |
        poetry-${{ runner.os }}-
  - run: poetry install --no-interaction

Gotchas

  • Key on poetry.lock, not pyproject.toml; the lock pins the exact resolved versions.
  • If you change the Python version, include it in the key so the cached venv is not reused on an incompatible interpreter.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →