GitLab - rules keyword

Today we are going to learn more about the rules keyword in GitLab. Normally, when you want to spawn your job on a specific branch or only in merge requests you can just use the only/except keywords. But, sometimes it is not enough. For example, what if you want to spawn a job always on develop branch and run it automatically, but in merge requests you want to run it manually? You cannot (easily) do that with the only/except keywords.

Excerpt from GitLab documentation about the rules keyword:

The rules keyword can be used to include or exclude jobs in pipelines. 
Rules are evaluated in order until the first match. When matched, the job is either included or excluded from the pipeline, depending on the configuration. If included, the job also has certain attributes added to it. 
rules replaces only/except and can’t be used in conjunction with it. If you attempt to use both keywords in the same job, the linter returns a key may not be used with rules error.

There are two very important things about this keyword:

  • either you use rules or only/except, you cannot use both of them
  • you can add two attributes to the rules keyword:
    • when
    • allow_failure

So, the rules keyword allows us to build more sophisticated pipelines. We are going to build a pipeline with the only/except keywords and then we will build a pipeline with the rules keyword.

Let's say that we want to run linters in merge requests only, build images automatically on develop, staging and master branches, and additionally, we also want to build an image in merge requests, but manually:

Hmm... I do not see the manual build job! Sadly, you cannot change the when keyword if you use the only/except keywords. So, let's resolve the problem with the rules keyword:

You can see two IFs and a default state (remember that rules are evaluated in order until the first match). In the first IF we check if a pipeline is in a merge request. If it is, then we change the value of when to manual. And, user can run this job manually. In the second IF we check if a branch name is develop, staging or master. If it is, we run the job always no matter what. The last step is a default state (you do not have to set up it). We just set up the value of when to never. That's all.

As you can see, your pipelines can be more sophisticated (not complicated!) with the rules keyword.

Here is also video!



Comments

Popular posts from this blog

GitLab - extends keyword

GitLab - trigger keyword

Managing Secrets in GitLab / Git