>_ IzzyLab

Hands-on task

This task is step 5 of the course “CI/CD: pipelines and docker compose”

GitLab CI: rules/if condition

medium~15 min

The project app (cloned to /root/app, the web sign-in is on the GitLab tab) already has CI: a lint job in the lint stage runs on every push. A runner is connected.

Add a unit job in the test stage to .gitlab-ci.yml: it runs the tests with python3 -m unittest -v, but only on the main branch — via rules with an if condition. Push to main and get a green pipeline with the unit job.

Then make sure the rule works: push the same commit to a new branch try-rules and look at its pipeline in GitLab — it must have only lint.

What you'll practise:
  • gitlab ci
  • rules
  • ci_commit_branch
  • conditional execution
  • yaml

Topic breakdown

rules is the modern replacement for the deprecated only/except: it's a list of conditions that GitLab checks top to bottom, and the first match decides the job's fate. An important nuance — if no rule matches, the job doesn't make it into the pipeline at all (a silent skip, not an error). Each element contains an if: with an expression over predefined variables ($CI_COMMIT_BRANCH — the current branch name) and optionally a when:; the condition is wrapped in single quotes so YAML doesn't try to parse its contents.

What's checked

  1. unit in the test stage with rules/if on the main branch
  2. unit runs on main and not on other branches or tags
  3. Latest pipeline on main is green
  4. The unit job in the test stage passed
  5. The try-rules branch pipeline has no unit

What it looks like