GitLab - include keyword

Some time ago GitLab has introduced include keyword that:

allows the inclusion of external YAML files.

Everyone knows that microservices like to multiply. Thus, this feature is very useful when you have microservices, because you do not have to copy & paste the code. Let's see what can you do with this.

Let's assume that we use Docker and we need to build an image. If you want to build an image and deploy your microservice you can just make a new .gitlab-ci.yml file in your project and add two jobs: build and deploy:

When you have three/four microservices you can tempt to copy & paste this code to the rest of the projects. But, if you have more projects and you need to change the logic of deployments, then you have a problem, because you need to edit many .gitlab-ci.yml files. You do not want to do that, so how to deal with it?

Use include keyword!

It is very simple. For me in most cases creating one gitlab template file is enough. Let's call it gitlab-template.yml. We need to store it somewhere. It does not have to be GitLab itself. You can store the file wherever you want. But I encourage you to use gitlab repo. You will have less problems. Let's create a repository where we are going to keep this file. Other microservices will include this file. Let's call the repo: ci-template and put gitlab-template.yml file on master branch. The content of this file is exactly as the above one.

Now, we want to include this file in our microservices repositories. We know the name of the repository, the name of the file, and the name of the branch, thus we can set up .gitlab-ci.yml file in our microservice:

In this way, when you create a new pipeline, your microservice project will merge the content of the file from ci-template project to .gitlab-ci.yml file.

Let's say that you want to add another step to your pipeline: tests. But, we do not have tests in all projects yet and a command for tests is not always the same. Can we still use include keyword? Of course!

We can add another section to gitlab-template.yml (the test section) file:

We pull an image and run linter in the before_script section. Additionally, in the script section, by default we just print information that you have not added any tests yet. If you want to add tests to your project you should overwrite the script section. How to do that? Remember that you can overwrite every job in your .gitlab-ci.yml file (which are "inherited" from gitlab-template.yml file). So, you can edit the script section:

Yeah, everything will be the same, you just changed the script section, nothing else. The job will pull an image, run linter (the before_script section) and run your tests without printing info that you have not added any tests because you overwrote the script section.

And that's it.

Video bonus:



Comments

Popular posts from this blog

GitLab - extends keyword

GitLab - trigger keyword

Managing Secrets in GitLab / Git