Skip to content

gitlab CI pipeline

gitlab CI pipeline

Recently gitlab platform becomes more and more popular. Not only does it provide the git version control, but also has embedded lots of useful devops related functionality. One of those is the option to build CI/CD pipelines, which is extremely useful for many projects. It allows you to automate tests and deployments. There are plenty of tutorials online on how to set such a pipeline up, including the official webpage. However, I want to show here how to build a more advanced CI pipeline, using different Docker images for different steps with conditions.

My custom Docker image takes some time to build, and for that reason I want to do it only when necessary. But when it is rebuild, I want to ensure that my tests are always run in proper containers.

I want to run unit tests with every branch commit. On top of that I want to execute regression tests when merge request is being created.

HOW TO

Let’s assume following:

  • all jobs are run in custom Docker containers
  • Docker image is rebuilt only when some changes to Dockerfile occur
  • images are tagged with git branch names for ease of tracing

To make sure image is build only if needed, the first job needs to be defined with a rule tracing file changes. The image is tagged using CI_COMMIT_REF_NAME gitlab variable, which will be useful for next steps.

 

Now I want to run unit tests with each commit to the branch, but using the newly created image in case commit changed the environment. Otherwise I want to use the existing latest image. I also want to ensure that if I add another commit to the branch (not changing the Dockerfile), tests still will execute on this newly-created image.

To do so I add an intermediate job to check whether branch related image exists (that’s where CI_COMMIT_REF_NAME comes in handy). As I want to enforce that this check is performed also when merge request is created, I define an if-when rule. Otherwise it would have run just once.

Job checks whether image for the branch was created (which only happens if Dockerfile was changed) and creates an artifact containing the name of the version of the image to use further.

 

Because this job creates an artifact, now my unit tests job can depend on it.

Tests will be run either on branch related image (if exists) or the current latest image.

 

Now for the merge request event I can run additional tests (like regression tests), using the same proper image.

 

Lastly, let’s exchange the current latest image, if new one was created, after the code merge.

 

Now let’s put all the pieces together, including the definition of the CURRENT_TAG variable.

Leave a Reply

Your email address will not be published. Required fields are marked *