Persisting Data Between Jobs in CircleCI Workflows
In CircleCI, jobs in a workflow are independent of each other and run in separate environments. This means that if you've done some work in one job (such as installing dependencies), you'll lose that work when moving to the next job. To make your pipelines more efficient, you can persist data across jobs using the persist_to_workspace
and attach_workspace
steps.
In the example configuration, we have a build
job where dependencies are installed, and we want to use those installed dependencies in a subsequent test
job. Here's how it works:
Persisting Data: In the
build
job, usepersist_to_workspace
to persist thenode_modules
directory. This will makenode_modules
available to subsequent jobs.- persist_to_workspace: root: . paths: - node_modules
Attaching Workspace: In the
test
job, useattach_workspace
to retrieve the data persisted from thebuild
job. We specify/workspace
as the directory where the persisted data should be attached.- attach_workspace: at: /workspace
Using Persisted Data: Finally, we run
npm test
in thetest
job using the previously installednode_modules
by setting theworking_directory
to/workspace
.
This approach is particularly useful for cutting down redundant steps in your workflow, making your CI/CD process more efficient.
For more details, you can refer to the official CircleCI documentation on Workspaces.
version: 2.1
jobs:
build:
docker:
- image: cimg/node:20.5.1
steps:
- checkout
- run: npm install
- persist_to_workspace:
root: .
paths:
- node_modules
test:
docker:
- image: cimg/node:20.5.1
steps:
- attach_workspace:
at: /workspace
- run:
command: npm test
working_directory: /workspace
workflows:
build_and_test:
jobs:
- build
- test:
requires:
- build