How can I trigger a gitlab pipeline job for a specific branch but not if the commit contains only changes to certain files? - gitlab

For example, I want a deploy job triggered but not if the commit contains changes relating to a Makefile and/or docker-compose.yml. How can I specify those rules/conditions? Thank to anyone who is willing to help.

this can be achieved with the rules block and the fact that the rules are evaluated sequentially and stop as soon as one rule applies.
Rules are evaluated when the pipeline is created, and evaluated in order until the first match. When a match is found, the job is either included or excluded from the pipeline, depending on the configuration.
https://docs.gitlab.com/ee/ci/yaml/#rules
this means you could do something like the following as a first rule, to ensure that it is never executed.
rules:
- changes:
- docker-compose.yml
when: never
Disclaimer: i did not test this, but based on the documentation it should work like this. see https://docs.gitlab.com/ee/ci/yaml/#rules for further details

Combine if rule to test the branch, and use changes condition to test if the file is in the changeset. Be sure to order them correctly to make sure the rule with changes is first.
my_job:
rules:
- if: '$CI_COMMIT_REF_NAME == "main"'
changes:
- makefile
- docker-compose.yml
when: never # dont run when these files are changed on this branch
- if: '$CI_COMMIT_REF_NAME == "main"'
when: on_success # otherwise run normally on this branch only
See rules:changes for more information.

Related

Gitlab CI when never

I saw this code on one of the pipelines of my company.
rules:
- if: 'SOME-CONDITION'
when: manual
- when: never
variables:
...
According to gitlab ci documentation, the when:never field should be used with a condition, to basically tell the pipeline to not add the job if that condition is satisfied. I don't understand its use by itself in the end of the rules. What does it add and how the pipeline will behave without it ?
The last when: never is not needed.
Even without that line, the job will run only if SOME-CONDITION is satisfied.

How to run gitlab stage periodically?

How can I run a gitlab stage periodically? I am aware of pipeline schedules documented here: https://docs.gitlab.com/ee/ci/pipelines/schedules.html. I am only interested in running a particular test stage of a branch. The issue is the branch I want to target has a lot of other stages involved with it. One option might be introducing a variable in the script portion that says if true then execute the script. However, this can be cumbersome and require a lot of changes to all the stages of the ci file for that particular branch under consideration.
You can control when your jobs run using the only/except keywords, or the more advanced rules keyword along with the pipeline source variable.
Example with only:
scheduled_test:
stage: tests
image: my_image:latest
only:
- schedules
script:
- ./run_some_things.sh
The only keyword lets you define some conditions that mean "this job only runs if these conditions are true", and offers a shorthand to check the source of the pipeline. schedules means that the pipeline was started from a schedule rather than a push, trigger, etc. The except keyword is just the opposite. If it had except: schedules the job would always run except if it was scheduled. You can see the full documentation for the only/except keywords here: https://docs.gitlab.com/ee/ci/yaml/#onlyexcept-basic
As of Gitlab version 12.3, the rules keyword extends the possibilities of the only/except options. We could get the same result from the example above like this:
scheduled_test:
stage: tests
image: my_image:latest
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: always
- if: '$CI_PIPELINE_SOURCE == "push"'
when: never
In this example, we check the predefined variable $CI_PIPELINE_SOURCE to see what started this pipeline. If it's "schedule", we always run this job. As an example, if the source is "push" (so the pipeline was started by a git push command), this job will never run. With the rules keyword, all if statements are OR'ed together, so the example above reads, if the source is schedule, always run OR if the source is a push, never run. However, you can AND multiple conditionals together in the same if:
rules:
- if: '$CI_PIPELINE_SOURCE == "push" && $MY_CUSTOM_VARIABLE == true'
when: manual
You can read the full documentation for the rules keyword here: https://docs.gitlab.com/ee/ci/yaml/#rules

How to quickly disable / enable stages in Gitlab CI

When you work on your .gitlab-ci.yml for a big project, for example having a time consuming testing stage causes a lot of delay. Is there an easy way to disable that stage, as just removing it from the stages definition, will make the YAML invalid from Gitlab's point of view (since there's a defined but unused stage), and in my case results in:
test job: chosen stage does not exist; available stages are .pre, build, deploy, .post
Since YAML does not support block comments, you'd need to comment out every line of the offending stage.
Are there quicker ways?
You could disable all the jobs from your stage using this trick of starting the job name with a dot ('.'). See https://docs.gitlab.com/ee/ci/jobs/index.html#hide-jobs for more details.
.hidden_job:
script:
- run test
There is a way to disable individual jobs (but not stages) like this:
test:
stage: test
when: manual
The jobs are skipped by default, but still can be triggered in the UI:
Also possible with rules and when as below:
test:
stage: test
rules:
- when: never
So far, the easiest way I've found is to use a rules definition like so:
test:
stage: test
rules:
- if: '"1" != "1"'
(...)
This still feels a bit odd, so if you have a better solution, I'll gladly accept another answer.

How can I trigger a job with a manual click OR a commit message

We have a job (deploy to production) that we generally manually click after checking that build on staging. However, very occasionally we have an issue that we've accidentally deployed and want to get a fix out ASAP. In those case we run the tests locally (much faster) and put [urgent-fix] in our commit message to stop the tests running in CI (skipping straight to Docker image build and staging deploy).
What we'd like to do is if we put [urgent-fix] it automatically triggers the production deploy (usually a when: manual step). Can we achieve this somehow?
Sounds like you can use a combination of the only:variables syntax and $CI_COMMIT_MESSAGE predefined variable.
A rough idea (untested):
.deploy_production: &deploy_production
stage: deploy production
script:
- echo "I'm deploy production here"
tags:
- some special tag
deploy::manual:
<< *deploy_production
when: manual
allow_failure: false
deploy:urgent_fix:
<< *deploy_production
only:
variables:
- $CI_COMMIT_MESSAGE =~/[urgent-fix]/
As of GitLab v12.3 (~September 2019) GitLab comes with "Flexible Rules for CI Build config". The feature is intended to replace the only/except functionality and is fully documented here.
With rules: you can now fully influence the when: behaviour of your job based on various conditions (in contrast to only/except: which forced you to create separate jobs for situations like the one described in the OP; see accepted answer).
For example you can do:
deploy:
rules:
- if: '$CI_COMMIT_TITLE =~ /urgent-fix/'
when: on_success
- when: manual # default fallback
script:
- sh deploy.sh
One thing to highlight is that in the above example I used $CI_COMMIT_TITLE instead of $CI_COMMIT_MESSAGE (see gitlab docs) to avoid the string "urgent-fix" reoccuring in a commit message automatically assembled in the course of a git merge, which would then accidentally retrigger the job.
Disclaimer: Please be aware that the new rules: feature stands in conflict with only/except: and thus requires you to remove only/except: occurences. Also, please note that rules: should only be used in combination with workflow: (read the docs) to avoid unwanted "detached" pipelines being triggered.

In GitLab CI, is there a variable for a Merge Request's target branch?

In my pipeline, I'd like to have a job run only if the Merge Requests target branch is a certain branch, say master or release.
Is this possible?
I've read through https://docs.gitlab.com/ee/ci/variables/ and unless I missed something, I'm not seeing anything that can help.
Update: 2019-03-21
GitLab has variables for merge request info since version 11.6 (https://docs.gitlab.com/ce/ci/variables/ see the variables start with CI_MERGE_REQUEST_). But, these variables are only available in merge request pipelines.(https://docs.gitlab.com/ce/ci/merge_request_pipelines/index.html)
To configure a CI job for merge requests, we have to set:
only:
- merge_requests
And then we can use CI_MERGE_REQUEST_* variables in those jobs.
The biggest pitfall here is only: merge_request has complete different behavior from normal only/except parameters.
usual only/except parameters:
(https://docs.gitlab.com/ce/ci/yaml/README.html#onlyexcept-basic)
only defines the names of branches and tags for which the job will run.
except defines the names of branches and tags for which the job will not run.
only: merge_request: (https://docs.gitlab.com/ce/ci/merge_request_pipelines/index.html#excluding-certain-jobs)
The behavior of the only: merge_requests parameter is such that only jobs with that parameter are run in the context of a merge request; no other jobs will be run.
I felt hard to reorganize jobs to make them work like before with only: merge_request exists on any job. Thus I'm still using the one-liner in my original answer to get MR info in a CI job.
Original answer:
No.
But GitLab have a plan for this feature in 2019 Q2: https://gitlab.com/gitlab-org/gitlab-ce/issues/23902#final-assumptions
Currently, we can use a workaround to achieve this. The method is as Rekovni's answer described, and it actually works.
There's a simple one-liner, get the target branch of an MR from the current branch:
script: # in any script section of gitlab-ci.yml
- 'CI_TARGET_BRANCH_NAME=$(curl -LsS -H "PRIVATE-TOKEN: $AWESOME_GITLAB_API_TOKEN" "https://my.gitlab-instance.com/api/v4/projects/$CI_PROJECT_ID/merge_requests?source_branch=$CI_COMMIT_REF_NAME" | jq --raw-output ".[0].target_branch")'
Explanation:
CI_TARGET_BRANCH_NAME is a newly defined variable which stores resolved target branch name. Defining a variable is not necessary for various usage.
AWESOME_GITLAB_API_TOKEN is the variable configured in repository's CI/CD variable config. It is a GitLab personal access token(created in User Settings) with api scope.
About curl options: -L makes curl aware of HTTP redirections. -sS makes curl silent(-s) but show(-S) errors. -H specifies authority info accessing GitLab API.
The used API could be founded in https://docs.gitlab.com/ce/api/merge_requests.html#list-project-merge-requests. We use the source_branch attribute to figure out which MR current pipeline is running on. Thus, if a source branch has multiple MR to different target branch, you may want to change the part after | and do your own logic.
About jq(https://stedolan.github.io/jq/), it's a simple CLI util to deal with JSON stuff(what GitLab API returns). You could use node -p or any method you want.
Because of the new env variables in 11.6 $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME and $CI_MERGE_REQUEST_TARGET_BRANCH_NAME jobs can be included or excluded based on the source or target branch.
Using the only and except (complex) expressions, we can build a rule to filter merge requests. For a couple examples:
Merge request where the target branch is master:
only:
refs:
- merge_requests
variables:
- $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"
Merge request except if the source branch is master or release:
only:
- merge_requests
except:
variables:
- $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME == "master"
- $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME == "release"
If you want to use multiple refs (let's say merge_requests and tags) and multiple variables, the refs will be OR'd, the variables will be OR'd, and the result will be AND'd:
If any of the conditions in variables evaluates to truth when using only, a new job is going to be created. If any of the expressions evaluates to truth when except is being used, a job is not going to be created.
If you use multiple keys under only or except, they act as an AND. The logic is:
(any of refs) AND (any of variables) AND (any of changes) AND (if kubernetes is active)
Variable expressions are also quite primitive, only supporting equality and (basic) regex. Because the variables will be OR'd you cannot specify both a source and target branch as of gitlab 11.6, just one or the other.
As of GitLab 11.6, there is CI_MERGE_REQUEST_TARGET_BRANCH_NAME.
If this is what you're really after, there could be an extremely convoluted way (untested) you could achieve this using the merge request API and CI variables.
With a workflow / build step something like:
Create merge request from feature/test to master
Start a build
Using the API (in a script), grab all open merge requests from the current project using CI_PROJECT_ID variable, and filter by source_branch and target_branch.
If there is a merge request open with the source_branch and target_branch being feature/test and master respectively, continue with the build, otherwise just skip the rest of the build.
For using the API, I don't believe you can use the CI_JOB_TOKEN variable to authenticate, so you'll probably need to create your own personal access token and store it as a CI variable to use in the build job.
Hope this helps!
Another example, but using rules:
rules:
# pipeline should run on merge request to master branch
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == 'master'
when: always
# pipeline should run on merge request to release branch
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == 'release'
when: always
- when: never
Gitlab CI is agnostic of Merge Requests (for now). Since the pipeline runs on the origin branch you will not be able to retrieve the destination.

Resources