How to trigger gitlab ci when a comment like "test please" is written in merge request discussion? - continuous-integration

I saw there are several ways to trigger the CI.
Even for merge requests
https://docs.gitlab.com/ee/ci/merge_request_pipelines/
What I want to do is to trigger a gitlab CI pipeline not for all merge request and not for all commits.
Only when someone comments:
'test please' or 'test gitlab' or some special keyword maybe defined by regex?
Is this possible?

That was requested in gitlab-org/gitlab-foss issue 39215, and shipped with 11.0
rspec:
script: ...
only:
variables:
- $CI_COMMIT_MESSAGE =~ /some-regexp/
You also have the following workaround for pipelines (windows cmd shell):
Process the job only if commit message doesn't contain [CI Release]
script:
- git show -s --format=%%B | findstr /C:"[CI Release]" >nul 2>&1 && (exit 0) || (set errorlevel=0)
- cd beUcb
- call mvn -N -Pver resources:resources
- REM ... rest of script ...

Related

How do I assign exe output to a variable in gitlab ci scripts?

When running my gitlab ci I need to check whether a specified svn directory exists.
I was using the script:
variables:
DIR_CHECK: "default"
stages:
- setup
- test
- otherDebugJob
.csharp:
only:
changes:
- "**/*.cs"
- "**/*.js"
setup:
script:
- $DIR_CHECK = $(svn ls https://server.fsl.local:port/svn/myco/personal/TestNotReal --depth empty)
- echo $DIR_CHECK
test:
script:
- echo "DIR_CHECK is blank"
- echo $DIR_CHECK
rules:
- if: $DIR_CHECK == ''
otherDebugJob:
script:
- echo "DIR_CHECK is not blank"
- echo $DIR_CHECK
rules:
- if: $DIR_CHECK != ''
the svn command works and echos back the correct reply but $DIR_CHECK does not get set to anything but the original default. It does not store the returned string from the svn command.
How do I store the returned string from an exe in a variable in gitlab ci?
Test run:
Executing "step_script" stage of the job script 00:00 $ $DIR_CHECK =
$(svn ls https://server.fsl.local:port/svn/myco/personal/TestNotReal
--depth empty) svn: E170000: Illegal repository URL https://server.fsl.local:port/svn/myco/personal/TestNotReal' $ echo
$DIR_CHECK Cleaning up file based variables 00:01 Job succeeded
Passing variables between jobs
Unfortunately, you cannot use DIR_CHECK variable the way you described. List of steps to be executed generates before steps actually runs, that means for all of the steps DIR_CHECK will be equal to default. First of all there are few tips how you can pass variables between jobs:
First way
You can add desired command to the before_script section in your .csharp template:
.csharp:
before_script:
- export DIR_CHECK=$(svn ls https://server.fsl.local:port/svn/myco/personal/TestNotReal --depth empty)
and extend other steps with this .csharp.
Second way
You can pass variables between jobs with job artifacts:
setup:
stage: setup
script:
- DIR_CHECK=$(svn ls https://server.fsl.local:port/svn/myco/personal/TestNotReal --depth empty)
- echo "DIR_CHECK=$DIR_CHECK" > dotenv_file
artifacts:
reports:
dotenv:
- dotenv_file
Thirds way
You can trigger or use parent/child pipelines to pass variables into pipelines.
staging:
variables:
DIR_CHECK: "you are awesome, guys!"
stage: deploy
trigger: my/deployment
In the triggered pipeline your variable will exists at the very start moment, and all the rules will be applied correctly.
Solution
In your case, if you really don't want to include otherDebugJob step in your pipeline you can do the following:
First approach
This is quite easy way and this will work, but looks like not a best practice. So, we are already know how to pass our DIR_CHECK variable from setup step , just add some check in the test step script block:
script:
- |
if [ -z "$DIR_CHECK" ]; then
exit 0
fi
- echo "DIR_CHECK is blank"
- echo $DIR_CHECK
Do the almost same thing for the otherDebugJob but check if DIR_CHECK is not empty with if [ -n "$DIR_CHECK" ].
This approach is helpful when your pipeline not contains a lot of steps, but after the test and otherDebugJob follows another few steps.
Second approach
You can fail your setup step and then handle this fail in otherDebugJob step:
setup:
script:
- DIR_CHECK=$(svn ls https://server.fsl.local:port/svn/myco/personal/TestNotReal --depth empty)
- |
if [ -z "$DIR_CHECK" ]; then
exit 1
fi
otherDebugJob:
script:
- echo "DIR_CHECK is not blank"
when: on_failure
This approach is useful if you only want to make some debug stuff after this setup step. After all on_failure jobs, pipeline will be marked as Failed and stopped.

Variable expansion of trigger branch property prevents downstream pipeline from being created

A branch job in which the branch property of the trigger property is using a variable will always fail with reason: downstream pipeline can not be created.
Steps to reproduce
Set up a downstream pipeline with a trigger property as you would normally.
Add a branch property to the trigger property. Write the name of an existing branch on the downstream repository, like master/main or the name of a feature branch.
Run the pipeline and observe that the downstream pipeline is successfully created.
Now change the branch property to use a variable instead, like branch: $CI_TARGET_BRANCH.
Manually run the CI pipeline with that, setting variable through the GitLab GUI.
The job will instantly fail with reason: downstream pipeline can not be created.
Code example
The goal is to create a GitLab CI config that runs the pipeline of a specified downstream branch. The bug occurs when attempting to do it with a variable.
This works, creating a downstream pipeline like normal. But the branch name is hardcoded:
stages:
- deploy
deploy:
variables:
environment: dev
stage: deploy
trigger:
project: group/project
branch: foo
strategy: depend
This does not work; although TARGET_BRANCH is set successfully, the job fails because the downstream pipeline can not be created:
stages:
- removeme
- deploy
before_script:
- if [ -z "$TARGET_BRANCH" ]; then TARGET_BRANCH="main"; fi
- echo $TARGET_BRANCH
test_variable:
stage: removeme
script:
- echo $TARGET_BRANCH
deploy:
variables:
environment: dev
stage: deploy
trigger:
project: group/project
branch: $TARGET_BRANCH
strategy: depend
If you know what I'm doing wrong, or you have something that does work with variable expansion of the branch property, please share it (along with your GitLab version). Alternate solutions are also welcome, but this one seems like it should work.
GitLab Version on which bug occurs
Self-hosted GitLab Community Edition 12.10.7
What is the current bug behavior?
The job always fails for reason: downstream pipeline can not be created.
What is the expected correct behavior?
The branch property should be set to the value of the variable and the downstream pipeline should be created as normal, just as if you simply hardcoded/typed the name of the branch.
More details
The ability to use variable expansion in the trigger branch property was added in v12.4, and it's explicitly mentioned in the docs.
I searched for other .gitlab-ci.yml / GitLab config files. Every single one that attempted to use variable expansion in the branch property had it commented out, saying it was bugged for an unknown reason (example.
I haven't been able to find a repository in which someone claimed to have a working variable expansion for the branch property of the trigger property.
Unfortunately, the alternate solutions are either (a) hardcoding every downstream branch name into the GitLab CI config of the upstream project, or (b) not being able to test changes to the downstream GitLab CI config without first committing them to master/main, or having to use only/except.
TL;DR: How to use the value of a variable for the branch property of a bridge job? My current solution makes it so the job fails and the downstream pipeline isn't created.
this is a 'works as designed', and gitlab will improve in upcoming releases.
trigger job will pretty weak b/c it is not a full job that runs on a runner. Therefore most of the trigger configuration needs to be hardcoded.
I use direct API calls to trigger downstream jobs passing the CI_JOB_TOKEN which links the upstream job to downstream as the trigger does
API calls give you full control
curl -X POST \
-s \
-F token=${CI_JOB_TOKEN} \
-F "ref=${REF_NAME}" \
-F "variables[STAGE]=${STAGE}" \
"${CI_SERVER_URL}/api/v4/projects/${CI_PROJECT_ID}/trigger/pipeline"
now this will not wait and monitor for when the job is done so you will need to code for that if you need to wait for the downstream job to finish,
Moreover, CI_JOB_TOKEN cannot be used to get the status of the downstream job, so you will another token for that.
- |
DOWNSTREAM_RESULTS=$( curl --silent -X POST \
-F token=${CI_JOB_TOKEN} \
-F "ref=${DOWNSTREAM_PROJECT_REF}" \
-F "variables[STAGE]=${STAGE}" \
-F "variables[SLS_PACKAGE_PATH]=.serverless-${STAGE}" \
-F "variables[INVOKE_SLS_TESTS]=false" \
-F "variables[UPSTREAM_PROJECT_REF]=${CI_COMMIT_REF_NAME}" \
-F "variables[INSTALL_SLS_PLUGINS]=${INSTALL_SLS_PLUGINS}" \
-F "variables[PROJECT_ID]=${CI_PROJECT_ID}" \
-F "variables[PROJECT_JOB_NAME]=${PROJECT_JOB_NAME}" \
-F "variables[PROJECT_JOB_ID]=${PROJECT_JOB_ID}" \
"${CI_SERVER_URL}/api/v4/projects/${DOWNSTREAM_PROJECT_ID}/trigger/pipeline" )
echo ${DOWNSTREAM_RESULTS} | jq .
DOWNSTREAM_PIPELINE_ID=$( echo ${DOWNSTREAM_RESULTS} | jq -r .id )
echo "Monitoring Downstream pipeline ${DOWNSTREAM_PIPELINE_ID} status..."
DOWNSTREAM_STATUS='running'
COUNT=0
PIPELINE_API_URL="${CI_SERVER_URL}/api/v4/projects/${DOWNSTREAM_PROJECT_ID}/pipelines/${DOWNSTREAM_PIPELINE_ID}"
echo "Pipeline api endpoint => ${PIPELINE_API_URL}"
while [ ${DOWNSTREAM_STATUS} == "running" ]
do
if [ $COUNT -eq 0 ]
then
echo "Starting loop"
fi
if [ ${COUNT} -ge 350 ]
then
echo 'TIMEOUT!'
DOWNSTREAM_STATUS="TIMEOUT"
break
elif [ $(( ${COUNT} % 60 )) -eq 0 ]
then
echo "Downstream pipeline status => ${DOWNSTREAM_STATUS}"
echo "Count => ${COUNT}"
sleep 10
else
sleep 10
fi
DOWNSTREAM_CALL=$( curl --silent --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" ${PIPELINE_API_URL} )
if [ $COUNT -eq 0 ]
then
echo ${DOWNSTREAM_CALL} | jq .
fi
DOWNSTREAM_STATUS=$( echo ${DOWNSTREAM_CALL} | jq -r .status )
COUNT=$(( ${COUNT} + 1 ))
done
#pipeline status is running, failed, success, manual
echo "PIPELINE STATUS => ${DOWNSTREAM_STATUS}"
if [ ${DOWNSTREAM_STATUS} != "success" ]
then
exit 2
fi

Gitlab-ci: extend script section

I have an unity ci-project.
.gitlab-ci.yml contains base .build job with one script command. Also I have multiple specified jobs for build each platform which extended base .build. I want to execute some platform-specific commands for android, so I have created separated job generate-android-apk. But if it's failing the pipeline will be failed too.(I know about allow_failure). Is it possible to extend script section between jobs without copy-pasting?
UPDATE:
since gitlab 13.9 it is possible to use !reference tags from other jobs or "templates" (which are commented jobs - using dot as prefix)
actual_job:
script:
- echo doing something
.template_job:
after_script:
- echo done with something
job_using_references_from_other_jobs:
script:
- !reference [actual_job, script]
after_script:
- !reference [.template_job, after_script]
Thanks to #amine-zaine for the update
FIRST APPROACH:
You can achieve modular script sections by utilizing 'literal blocks' (using |) like so:
.template1: &template1 |
echo install
.template2: &template2 |
echo bundle
testJob:
script:
- *template1
- *template2
See Source
ANOTHER SOLUTION:
Since GitLab 11.3 it is possible to use extend which could also work for you.
.template:
script: echo test template
stage: testStage
only:
refs:
- branches
rspec:
extends: .template1
after_script:
- echo test job
only:
variables:
- $TestVar
See Docs
More Examples

How to set customized displayName to a Jenkins pipeline job?

One of my customers has some freestyle Jenkins jobs which display "#${BUILD_NUMBER}|${BRANCH_NAME}"
In the description or displayName of the jobs using a plugin called "Build Name Setter".
Unfortunately, this plugin works properly only in freestyle jobs.
I want to achieve the same goal but with a Jenkins pipeline job.
I've tried adding the following line, just after the checkout step:
currentBuild.displayName = "#${BUILD_NUMBER}|${BRANCH_NAME}"
But I'm getting an error that "BRANCH_NAME" is not set.
I must use the "SCM step" instead of a dedicated plugin because the repository I'm cloning is a TFS-Git repository and it's plugin doesn't have this functionality.
This is a known issue in the behavior of SCM step specifically in pipeline jobs, but I was wondering if any of you found any workaround which I can implement to display this information in the job's page.
I solved it by doing something very close to what #haschibaschi suggested but in my case I wrote the BRANCH_NAME to a groovy file in the workspace and loaded it into the BRANCH_NAME variable.
stage ('Checkout SCM') {
checkout([$class: 'GitSCM', branches: [[name: '*/feature/*']], doGenerateSubmoduleConfigurations: false, extensions: [], url: 'http://TFS_SERVER:8080/tfs/DefaultCollection/PC_International/_git/project']]])
bat """
cd %workspace%
set branch="git rev-parse --abbrev-ref HEAD"
FOR /F "tokens=*" %%i IN (' %branch% ') DO SET BRANCH_NAME=%%i
echo %BRANCH_NAME% > BRANCH_NAME.groovy
"""
BRANCH_NAME = readFile('BRANCH_NAME.groovy')
currentBuild.displayName = "# ${BUILD_NUMBER} | ${BRANCH_NAME}"
}
Now the relevant information is displayed as the name of the build:
Just get the branch name manually and assign it to BRANCH_NAME.
Something like this (didn't verify the code):
dir("checkoutdir") {
BRANCH_NAME = sh (
script= "git branch | grep \* | cut -d ' ' -f2'",
returnStdout: true
).trim()
}
echo "branchname: $BRANCH_NAME"
In a Jenkinsfile, ${env.BRANCH_NAME} should work.

How to run a specific job in gitlab CI

We are facing a problem where we need to run one specific job in gitlab CI. We currently not know how to solve this problem. We have multitple jobs defined in our .gitlab-ci.yml but we only need to run a single job within our pipelines. How could we just run one job e.g. job1 or job2? We can't use tags or branches as a software switch in our environment.
.gitlab-ci.yml:
before_script:
- docker info
job1:
script:
- do something
job2:
script:
- do something
You can use a gitlab variable expression with only/except like below and then pass the variable into the pipeline execution as needed.
This example defaults to running both jobs, but if passed 'true' for "firstJobOnly" it only runs the first job.
Old Approach -- (still valid as of gitlab 13.8) - only/except
variables:
firstJobOnly: 'false'
before_script:
- docker info
job1:
script:
- do something
job2:
script:
- do something
except:
variables:
- $firstJobOnly =~ /true/i
Updated Approach - rules
While the above still works, the best way to accomplish this now would be using the rules syntax. A simple example similar to my original reply is below.
If you explore the options in the rules syntax, depending on the specific project constraints there are many ways this could be achieved.
variables:
firstJobOnly: 'false'
job1:
script:
- do something
job2:
script:
- do something
rules:
- if: '$firstJobOnly == "true"'
when: never
- when: always
We faced the same problem in the past and I'm sharing with you our solution.
#Remark#
I read the answer of Jawad and I found it good and we have tried it when we faced the issue.
My remark is that adding when: manual will always show ALL your jobs in the pipeline.
So if you work in a large team, you can't prevent other collaborators to click by error or by mistake on the job you don't want to be launched.
#What I'm supposing before continuing#
Let's say that you have 4 jobs.
You need to always run (manually or automatically) job 1, job 2 and job 4 but NOT job3.
You want to only run job 3 in a specific case or just when you decide to run it.
#The idea is#
We launch the 3rd job only for tags which match a regular expression.
In the example below, it's launched for tags like helloTag.1, helloTag.2, helloTag.3... etc.
If we are in develop or master (or other branch), we will have 3 stages (stage 1, stage 2, stage 4)
Note how the 3rd job is not present in the pipeline
Go to "Repository" --> "Tags" --> "New tag"
Give the tag a name which much your regular expression
If we are in a tag having a name which starts with "helloTag.", we will have 1 stage (stage 3)
Note how other stages are not present here
#Example of .gitlab-ci file#
stages:
- myStage1
- myStage2
- myStage3
- myStage4
This is my first stage:
stage: myStage1
before_script:
- echo "my stage 1 before script"
script:
- echo "my stage 1 script"
except:
- /^helloTag.*$/
This is my second stage:
stage: myStage2
before_script:
- echo "my stage 2 before script"
script:
- echo "my stage 2 script"
except:
- /^helloTag.*$/
This is my third stage:
stage: myStage3
before_script:
- echo "my stage 3 before script"
script:
- echo "my stage 3 script"
only:
- /^helloTag.*$/
This is my fourth stage:
stage: myStage4
before_script:
- echo "my stage 4 before script"
script:
- echo "my stage 4 script"
except:
- /^helloTag.*$/
Hope that this helps you.
Simply add a when: manual to the jobs you don't want to run.
These jobs will still appear in your pipeline but won't be run, unless someone "manually" starts them through the web interface, hence the name.
Here's more info about this: https://docs.gitlab.com/ce/ci/yaml/README.html#when
If you're looking for something more "programmable", let's say run either job1 or job2 depending on a branch name or a tag, then you should have a look at the only and except keywords: https://docs.gitlab.com/ce/ci/yaml/README.html#only-and-except
> Currently it seems not to be possible with GitLab CI to have other software switches than tags or branches as provided in the other answers.
We finally switched to an other "real" CI due to too many limitations on GitLab CI. GitLab CI is unfelixble if you want to run some custom jobs in different procedures. I realy appreciated the both answers here. I'm sure they will help other users to manage this stuff. Unfortunately in our case we could not use tags, commit messages or branches as a software switch.
We are still looking for a answer on this. Feel free to give an other approach to solve this problem. I will mark the right answer once it hits. Also a bounty on this question did not result in an right answer.
The original question asks how to trigger jobs without using branch-names or tags. This leaves commit messages and environment variables as viable sources, and neither require editing your yaml file for each push.
Commit Messages
Job rules with commit message regex is a very simple and flexible solution, in my experience.
Set up your .gitlab-ci.yml like this
job1:
...
rules:
- if: '
$CI_COMMIT_MESSAGE =~ /.*run job1.*/ ||
$CI_COMMIT_MESSAGE =~ /.*run all.*/
'
job2:
...
rules:
- if: '
$CI_COMMIT_MESSAGE =~ /.*run job2.*/ ||
$CI_COMMIT_MESSAGE =~ /.*run all.*/
'
Push with a commit message like this
git commit --allow-empty -m "testing conditional job triggers for gitlab-ci based on branch names and commit messages. run job1"
git push
You'll notice this also allows you to run both jobs with a message like this
git commit --allow-empty -m "testing all jobs. run all"
git push
Environment Variables
Elsewhere in your answer to your own question you add a constraint: commit messages cannot be used. Environment variables can be set in the git cli
Set up your .gitlab-ci.yml like this
job1:
...
rules:
- if: $JOB1
job2:
...
rules:
- if: $JOB2
Push like this
git commit --allow-empty -m "triggering job1 with ci variables"
git push -o ci.variable="JOB1=anythingAtAll"
reference: https://docs.gitlab.com/ee/user/project/push_options.html

Resources