Certainly! Below is an example of an Azure DevOps CI pipeline YAML script that caches Python pip packages:
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
variables:
pythonVersion: '3.8'
PIP_CACHE_DIR: $(Pipeline.Workspace)/.pip
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '$(pythonVersion)'
addToPath: true
- task: Cache@2
inputs:
key: 'pip | "$(Agent.OS)" | $(pythonVersion) | $(Build.SourcesDirectory)/requirements.txt'
restoreKeys: |
pip | "$(Agent.OS)" | $(pythonVersion)
path: $(PIP_CACHE_DIR)
displayName: 'Cache pip'
- script: |
python -m pip install --upgrade pip
pip install --cache-dir=$(PIP_CACHE_DIR) -r $(Build.SourcesDirectory)/requirements.txt
displayName: 'Install dependencies'
Let me explain what each part of the script does:
-
trigger: This specifies which branch(es) will trigger the build. In this case, any push to the main branch will trigger the pipeline.
-
pool: This specifies the type of build agent to use. The vmImage is set to 'ubuntu-latest', which will run the build on the latest version of Ubuntu provided by Azure.
-
variables: We define two variables, pythonVersion to specify the Python version to use and PIP_CACHE_DIR to define the path to the cache directory for pip.
-
UsePythonVersion@0: This task is used to specify the Python version that will be used in the build. It's set to use the version specified by the pythonVersion variable.
-
Cache@2: This task is used to cache the pip packages. The key is used to define what will trigger a cache restore. The path specifies where the cache is located. The restoreKeys is a fallback mechanism to restore the cache in case the primary key doesn't match.
-
script: The last step is a script that first upgrades pip to the latest version and then installs the required packages from the requirements.txt file using the cache directory specified by PIP_CACHE_DIR.
This script assumes you have a requirements.txt in the root of your source directory ($(Build.SourcesDirectory)). The cache will be saved and restored based on the key that includes the OS type, Python version, and the hash of the requirements.txt file. If any of these change, the cache will be updated on the next run.