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 trueso the venv lives at.venv. - Cache
.venvkeyed onhashFiles('**/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-interactionGotchas
- Key on
poetry.lock, notpyproject.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
How to Cache pip Downloads in GitHub ActionsCache the pip download cache in GitHub Actions by resolving pip cache dir and keying the cache on requirement…
How to Cache the uv Cache in GitHub ActionsCache the uv package cache in GitHub Actions, keyed on uv.lock, so the uv Python package manager reuses its w…