Middle
How to use GitLab CI to preserve data between multiple build stages?
sobes.tech AI
Answer from AI
Artifacts are used in GitLab CI to preserve data between build stages. These are files or directories created in one stage and accessible in subsequent stages.
The configuration in .gitlab-ci.yml looks like this:
stages:
- build
- test
- deploy
build_job:
stage: build
script:
- echo "Build result" > build_output.txt # Create a file
artifacts:
paths: # Specify which files/directories to save
- build_output.txt
expire_in: 1 week # Artifact retention period
test_job:
stage: test
script:
- cat build_output.txt # Access the file from the previous stage
- npm test
needs: # Specify dependency on the previous stage
- build_job
deploy_job:
stage: deploy
script:
- deploy_script.sh
needs:
- test_job
Key elements:
artifacts: Defines which files or directories should be saved after the stage.paths: List of file or directory paths that will become artifacts.expire_in: Specifies how long the artifacts will be available.needs: Explicitly states the dependency of the current stage on the previous one. GitLab CI will automatically download artifacts from the specified stages before executing the current one.
Without needs, GitLab CI will download artifacts from all previous stages in the same or earlier stage, which may be inefficient. Explicit dependencies with needs more precisely control which artifacts are loaded.
You can also use cache to save dependencies, such as installed packages, but it is intended to speed up repeated builds rather than passing results from one stage to another. Artifacts are the primary mechanism for passing output data between stages.