Overriding a GitLab CI/CD pipeline job

Introduction
To override a GitLab CI/CD pipeline job, you can achieve this by defining a job with the same name in your local .gitlab-ci.yml file as the job you wish to override. GitLab's CI/CD configuration merging mechanism ensures that the configuration defined in your local .gitlab-ci.yml takes precedence over any included or inherited configurations when job names are identical.
Here's how this works:
Identify the job to override:
Locate the job in your included or template CI/CD configuration that you want to modify.
Create a job with the same name:
In your project's
.gitlab-ci.ymlfile, define a new job with the exact same name as the target job.Specify the desired changes:
Within this new job definition, include the specific configurations you want to override. This could involve:
- Changing the
script: Modify the commands executed by the job. - Adjusting
variables: Override or add new CI/CD variables specific to that job. - Modifying
rulesoronly/except: Control when the job runs. - Updating
stageortags: Assign the job to a different stage or runner. - Adding
before_scriptorafter_script: Introduce commands to run before or after the main script.
- Changing the
Example:
If you have an included template with a job named build_app:
# .gitlab-ci-template.yml
build_app:
stage: build
script:
- echo "Building application from template"
- make build
You can override it in your project's .gitlab-ci.yml by defining a job with the same name:
# .gitlab-ci.yml
include:
- local: .gitlab-ci-template.yml
build_app:
script:
- echo "Building application with custom logic"
- custom_build_script.sh
variables:
CUSTOM_VAR: "true"
In this example, the build_app job in .gitlab-ci.yml will override the script and add a new variable to the build_app job defined in .gitlab-ci-template.yml. The stage will be inherited from the template unless explicitly overridden.
Conclusion
As you can see, it's quite simple to achieve a job definition override in gitlab. This allows for a templated job defition to be used and re-used in as many jobs as necessary as well as the flexibility to re-define the said job when there is a specific use case that requires it.




