My take on how to create a re-usable function (of sorts) in CICD pipeline.
Problem Statement
Had to create multiple Docker images with respective Dockerfile's and in parallel
The original code design was to create multiple jobs with a basic dependency structure & let them build respective docker images in parallel
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!
Export variables that we need to pass as arguments & use them in generic function
These export statements should be before ! reference call to the generic function
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