How to Cache Dependencies in Azure Pipelines
The Cache@2 task restores a saved package store keyed on your lockfile, so a clean install only runs when dependencies actually change.
Add a Cache@2 step before install. Set key to a hashed lockfile and path to the package store. On a hit the task restores it; on a miss it saves the path after the job succeeds.
Steps
- Add
Cache@2before your install step. - Set
keyto a string that includes the OS and a lockfile hash. - Point
pathat the dependency store (for example the npm cache). - Add
restoreKeysfor a partial fallback when the exact key misses.
Pipeline
azure-pipelines.yml
steps:
- task: Cache@2
inputs:
key: 'npm | "$(Agent.OS)" | package-lock.json'
restoreKeys: |
npm | "$(Agent.OS)"
path: $(Pipeline.Workspace)/.npm
displayName: Cache npm
- script: |
npm config set cache $(Pipeline.Workspace)/.npm --global
npm ci
displayName: InstallGotchas
- The cache is saved only when the job succeeds, so a failing job never seeds the cache.
- Keys are immutable; change the key (not the contents) when you want a fresh cache.
- Cache an install directory you can rebuild, not source you need fetched fresh.
Related guides
How to Publish and Download Pipeline Artifacts in Azure PipelinesMove build output between jobs in Azure Pipelines with PublishPipelineArtifact and DownloadPipelineArtifact,…
How to Run Jobs in Parallel With a Matrix in Azure PipelinesFan one Azure Pipelines job out into parallel jobs with a matrix strategy, defining named legs that each set…