GitLab CICD - How to create a re-usable function with arguments

Photo by Sabri Tuzcu on Unsplash

GitLab CICD - How to create a re-usable function with arguments

My take on how to create a re-usable function (of sorts) in CICD pipeline.

Problem Statement

  1. Had to create multiple Docker images with respective Dockerfile's and in parallel

  2. The original code design was to create multiple jobs with a basic dependency structure & let them build respective docker images in parallel

  3. When the code was completed, I was not happy with how the entire code was structured, I was using the same steps over & over with different hard-coded inputs

I was badly looking for an option on how to create a generic function which can accept arguments and do the repetitive image build steps.

Here is an example,

  • line # 9 - 11 & # 17 - 19 are repeating in both jobs with only differences in values

After referring to multiple StackOverflow responses & GitLab documentation came across the concept of "! reference". Here is how I was able to use it.

Solution - but wait, not complete without argument

On the first implementation of ! reference, was able to call generic function but job # 2 was also printing the same values as job # 1. The question is how do I pass arguments?

  • .common-functions.yml

  • .gitlab-ci.yml

  • Output from job # 2

Solution - finally worked!

  1. Export variables that we need to pass as arguments & use them in generic function

  2. These export statements should be before ! reference call to the generic function

  3. Now, the generic function can take this value from the environment

  • .common-functions.yml

  • .gitlab-ci.yml

  • Output of job # 1

  • Output of job # 2

Now entire code was modularized & manageable.

Reference

https://docs.gitlab.com/ee/ci/yaml/yaml_optimization.html#reference-tags