Question
Answer and Explanation
To configure GitLab to run pipeline jobs only on the master
branch, you'll need to modify your .gitlab-ci.yml
file. The rules
keyword is the most straightforward method to achieve this.
Here's how you can set it up:
1. Using the 'rules' Keyword: The rules
keyword allows you to specify conditions under which a job should run. We can use this to filter for the master
branch.
- Modify your .gitlab-ci.yml
file to include rules
in each job definition. Here’s an example that defines a basic job:
job_name:
script:
- echo "This job runs only on the master branch"
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
2. Explanation of the Code:
- job_name
: Replace this with the actual name of your job.
- script
: The commands that your job will execute.
- rules
: Defines when this job should be executed. In this case, it will only run when the condition specified in the if
clause is met.
- if: '$CI_COMMIT_BRANCH == "master"'
: This line specifies that the job should run only if the value of the CI_COMMIT_BRANCH
environment variable is equal to "master"
. CI_COMMIT_BRANCH
is a predefined variable in GitLab CI that contains the branch name of the commit that triggered the pipeline.
3. Example with Multiple Jobs:
If you have multiple jobs, each can have its own rules
:
job_build:
script:
- echo "Building the application"
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
job_test:
script:
- echo "Running tests"
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
job_deploy:
script:
- echo "Deploying to production"
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
4. Alternative using 'only' (Deprecated): An older method used the only
keyword, but rules
is preferred as it is more powerful and flexible:
job_name:
script:
- echo "This job runs only on the master branch"
only:
- master
Note that while this approach works, rules
is recommended for new configurations.
5. Common Pitfalls:
- Ensure correct syntax in .gitlab-ci.yml
. YAML is sensitive to spacing and indentation.
- Double check branch names. "master" is case-sensitive.
By using the rules
keyword with the conditional if: '$CI_COMMIT_BRANCH == "master"'
, you can accurately configure your GitLab pipeline to run jobs only on the master branch. This will help ensure that specific deployment or testing jobs are only executed when changes are merged into the main branch.