Middle
What are the differences between artifacts and cache in GitLab CI as job attributes?
sobes.tech AI
Answer from AI
Artifacts and cache in GitLab CI serve to speed up build and testing processes, but they have different functions and purposes.
Artifacts:
- Purpose: To save the results of a job (builds, tests, documentation, etc.) for later use or review. They can be downloaded manually or accessed via the web interface.
- Lifetime: Defined by the
.gitlab-ci.ymlsettings. They can be deleted after a certain period or kept. - Size: Usually larger than cache, as they contain completed builds, reports, and other results.
- Usage: To transfer results between jobs in different stages or to provide them to users.
Example configuration:
artifacts:
paths: # paths to files and directories that will become artifacts
- build/
- test-results.xml
expire_in: 1 week # artifact lifetime
Cache:
- Purpose: To save project dependencies or intermediate results to speed up subsequent runs of the same job. Cache is tied to a specific branch or tag (configurable).
- Lifetime: Managed automatically by GitLab. Old cache entries are deleted when quotas are exceeded or the expiration date is reached. Cache can be automatically restored or created on a new run.
- Size: Usually smaller than artifacts, as it contains dependencies like Maven repositories, npm packages, etc.
- Usage: To speed up dependency installation and reduce build time.
Example configuration:
cache:
paths: # paths to directories to be cached
- node_modules/
- ~/.m2/repository/
key: # cache key, can use predefined variables
files:
- package-lock.json # cache will update when this file changes
prefix: ${CI_COMMIT_REF_SLUG} # adds a prefix with branch/tag name
Key differences:
| Attribute | Artifacts (artifacts) | Cache (cache) |
|---|---|---|
| Purpose | Saving job results | Saving dependencies to speed up |
| Usage | Downloading, transferring between jobs (different stages) | Automatic restoration/creation |
| Lifetime | Explicitly set in .gitlab-ci.yml configuration |
Managed by GitLab, automatic deletion |
| Access | Via web interface, API | Automatically used by Runner |
| Branch relation | No direct link (unless explicitly specified) | Usually tied to a branch for isolation |
Thus, artifacts are the output data of a build, while cache is the reused components to accelerate the build itself.
job_example:
stage: build
script:
- echo "Building and testing..."
- mkdir build
- echo "Build result" > build/result.txt
- echo "dependency installation"
cache:
paths:
- dependency_dir/ # folder with dependencies, will be cached
artifacts:
paths:
- build/ # build folder will become an artifact