Azure DevOps中Poetry安装缓存优化:改写Pipeline YAML
Azure DevOps Pipeline 缓存优化方案(Test+Build阶段)
核心思路
- 借助Azure DevOps的
Cache任务,基于poetry.lock文件的哈希值生成缓存键,只要依赖锁文件不变,就复用已安装的Poetry环境和依赖包 - 统一配置Poetry虚拟环境路径,确保缓存路径可预测
- Test阶段先完成依赖安装与测试,Build阶段复用缓存直接执行构建操作
优化后的YAML示例
trigger: - main variables: # 定义Poetry虚拟环境路径,方便缓存 POETRY_VENV_PATH: $(Agent.TempDirectory)/.venv # 缓存键前缀,结合lock文件哈希 CACHE_KEY: 'poetry-$(Agent.OS)-$(HashFiles(''**/poetry.lock''))' # 缓存失效时的回退键 CACHE_FALLBACK_KEY: 'poetry-$(Agent.OS)-' stages: - stage: Test jobs: - job: TestJob pool: vmImage: 'ubuntu-latest' # 根据需求更换镜像,比如windows-latest steps: - task: Cache@2 displayName: 'Cache Poetry Dependencies' inputs: key: '$(CACHE_KEY)' restoreKeys: | $(CACHE_FALLBACK_KEY) path: '$(POETRY_VENV_PATH)' - script: | # 安装Poetry(缓存未命中时执行) curl -sSL https://install.python-poetry.org | python3 - # 将Poetry加入环境变量 echo "PATH=$HOME/.local/bin:$PATH" >> $GITHUB_ENV displayName: 'Install Poetry' condition: ne(variables['CacheRestored'], 'true') - script: | poetry config virtualenvs.path $(POETRY_VENV_PATH) poetry install --no-root displayName: 'Install Dependencies' condition: ne(variables['CacheRestored'], 'true') - script: | poetry run pytest displayName: 'Run Tests' - stage: Build dependsOn: Test jobs: - job: BuildJob pool: vmImage: 'ubuntu-latest' # 和Test阶段保持一致镜像 steps: - task: Cache@2 displayName: 'Restore Poetry Dependencies' inputs: key: '$(CACHE_KEY)' restoreKeys: | $(CACHE_FALLBACK_KEY) path: '$(POETRY_VENV_PATH)' - script: | curl -sSL https://install.python-poetry.org | python3 - echo "PATH=$HOME/.local/bin:$PATH" >> $GITHUB_ENV displayName: 'Install Poetry' condition: ne(variables['CacheRestored'], 'true') - script: | poetry config virtualenvs.path $(POETRY_VENV_PATH) poetry install --no-root displayName: 'Install Dependencies' condition: ne(variables['CacheRestored'], 'true') - script: | poetry build displayName: 'Build Package'
关键部分说明
- 缓存配置:
Cache@2任务通过poetry.lock的哈希值判断是否恢复缓存,锁文件未修改时直接复用虚拟环境,跳过重复安装步骤 - 条件判断:
condition: ne(variables['CacheRestored'], 'true')确保仅在缓存未命中时执行Poetry和依赖安装 - 虚拟环境路径:统一指定
POETRY_VENV_PATH,保证缓存路径稳定,避免环境差异导致缓存失效
内容的提问来源于stack exchange,提问作者Lilac
相关产品推荐
相关产品推荐

