Dynamic branch name for a downstream job in Gitlab CI/CD
Your project’s CICD has reached a point where you need to trigger the pipeline of another project. Thanks to the multi-projects pipelines, you have managed to extend the workflow of your pipeline by allowing it to trigger the pipeline for another project.
Here is a basic example :
By default the trigger job will use the default branch of the triggered project or the branch specified in in the keyword
branch. Unfortunately the project you want to trigger is not always on the same branch.
Two solutions at the time of writing this article.
1) Passing the branch name with custom environnement variables
Use the global keywork
variable to pass the branch name to your downstream job.
The problem of this solution is that you have to specify the content of the variable
MY_APP_BRANCH when triggering the pipeline so that the default content is overwritten. It can be a solution when a pipeline is launched manually from the web interface or with the API but not really when it’s done throught commit, pull requests and others git commands.
2) Using a job to pass environment variables to other jobs
This solutions will probably better suit your needs. The idea is to create a job that will create a
dotenvreport artifact that will be automatically loaded by the trigger job.
Here is the trick.
- echo "MY_APP_BRANCH=my-dynamic-branch-name" >> build.env
Now when the trigger job is launched, it will set the
MY_APP_BRANCH content as defined in the job that created the dotenv report.
Here it is, you can now pass dynamic branch variables to your downstream jobs!