In GitLab CI/CD, you can configure your pipeline jobs to run only when files in a specific directory have changed. This is done using the only and changes keywords in your .gitlab-ci.yml file.
Here's how you can set it up
1. Using changes Keyword
The changes keyword allows you to specify which files or directories should trigger the job. If any files in the specified path are modified, the job will run.
Example: Run job only if files in src/ directory change
job_name:
script:
- echo "This job runs when files in the src/ directory change."
only:
changes:
- src/*In this example
- The job will only run when any file inside the
src/directory is modified. - The
src/*pattern includes all files in thesrcdirectory.
2. Using Multiple Directories or Files
You can specify multiple files or directories by providing an array of paths under the changes keyword.
Example: Run job if files in src/ or docs/ directories change
job_name:
script:
- echo "This job runs when files in src/ or docs/ directories change."
only:
changes:
- src/*
- docs/*This setup triggers the job when there are changes in either the src/ or docs/ directories.
3. Combining changes with Other Conditions
You can also combine changes with other conditions like branches, tags, or variables.
Example: Run job only on main branch and if files in src/ change
job_name:
script:
- echo "This job runs only on main branch when files in the src/ directory change."
only:
changes:
- src/*
refs:
- main4. Full Example
Here's a full .gitlab-ci.yml example that runs a job only when files in the src/ or assets/ directories change, and only on the main branch.
stages:
- build
build_job:
stage: build
script:
- echo "Running build job because files in src/ or assets/ changed."
only:
changes:
- src/*
- assets/*
refs:
- mainHow It Works
- GitLab compares the changed files in the latest commit with the files from the previous commit.
- If the files in the specified paths are modified, the job will be triggered.
- This is a useful way to optimize your CI/CD pipeline by avoiding unnecessary jobs and saving resources.
By using the changes keyword, you ensure your pipeline runs only when relevant changes are made, which improves efficiency.