before_script and after_script in GitLab CI/CD pipelines to install dependencies and handle cleanup. We’ll demonstrate using the cowsay gem to generate fun ASCII artwork.
- A GitLab project with CI/CD enabled
- Basic understanding of GitLab CI/CD YAML syntax
- Docker runner or shared runners configured
Table of Contents
- Define OS Version Jobs
- Generate ASCII Artwork with cowsay
- Pipeline Failure: Missing Dependency
- Install Dependencies with before_script
- Successful Job Output
- Summary
- Links and References
Define OS Version Jobs
Create lightweight jobs to display OS versions on various runners:Generate ASCII Artwork with cowsay
Define a pipeline that usescowsay to output ASCII art into a file:
Pipeline Failure: Missing Dependency
Running the above job on the default Ruby image fails:cowsay is not preinstalled in the base image.
Install Dependencies with before_script
To ensurecowsay is available, install it via before_script:
| Keyword | Purpose | Example |
|---|---|---|
| before_script | Install dependencies or prepare environment before script | - gem install cowsay |
| script | Main steps of the job | ASCII generation commands |
| after_script | Cleanup or notifications after the job | - echo "Cleanup after job" |
Ensure your runner can access external package sources. For air-gapped environments, pre-build a custom Docker image with required gems.
Successful Job Output
Withcowsay installed, the pipeline completes successfully:
Summary
By adding abefore_script section to your GitLab CI/CD job, you can:
- Automatically install required libraries or tools
- Avoid failures due to missing dependencies
- Leverage
after_scriptfor cleanup and notifications