How make a if statement in the CI file

Have somebody a simple example how to make if conditions in the CI file for GitLab Runner?

E.g.

If(CI_type == merge_request)
{
- echo „ Test“
}

Hi,

I’m afraid, this is not possible in the relatively static YAML configuration language. I would write a small bash script which reads the environment variables CI_MERGE_REQUEST_ID and does the printing then. Whenever the ID is filled with content, this is a merge request.

vim run.sh

#!/bin/bash

if [ "$CI_MERGE_REQUEST_ID" != "" ]; then
  echo "Test"
fi

Before adding that to your CI config, you can test it locally.

CI_MERGE_REQUEST_ID=42 bash run.sh

Add the script into the main directory, or yet better, in a dedicated sub directory.

mkdir -p .gitlab/ci
vim .gitlab/ci/run.sh

chmod +x .gitlab/ci/run.sh
git add .gitlab/ci/run.sh
git commit -v

Then add it to your CI job config.

vim .gitlab-ci.yml

myjob:
  script:
  - ./.gitlab/ci/run.sh

Cheers,
Michael

Thanks works

Can you not use rules for this in gitlab-ci.yml or have I misunderstood the question?

myjob:
    rules:
        - if: $CI_MERGE_REQUEST_ID
          when: always
        - when: never
    script:
        - echo "Test"

or, if there’s some reason why you need this in a longer if statement:

myjob:
    rules:
        - when: always
    script:
        - |- 
            if [[ $CI_MERGE_REQUEST_ID != "" ]]; then
                echo "Test"
            fi
```
1 Like

Hi,

true that, I have not fully adopted rules into my mindset yet.

One thing for rules though: The condition matches the entire job scope, you cannot split 2 statements with different conditions (to my knowledge).

Since I am also overwhelmed by code in YAML config, I usually refactor more complex logic into helper scripts. Exceptions are for workshops to show the thinking steps in verbose mode.

Cheers,
Michael

I’m not sure what you mean by “you cannot split 2 statements with different conditions”? You can do things like:

    rules:
        - if: '$CI_COMMIT_BRANCH =~ /^release\/[a-z0-9-\.]+$/'
          when: always
        - if: $CI_COMMIT_TAG
          when: never
        - when: never

or:

    rules:
        - if: '$CI_COMMIT_BRANCH =~ /^release\/[a-z0-9-\.]+$/' && $CI_COMMIT_TAG != ""
          when: always
        - when: never

but if you want part of the script to run on different conditions, you’d need a multiline Bash statement with:

script: 
    - |- 
            if [[ $CI_MERGE_REQUEST_ID != "" ]]; then
                echo "Test"
            else 
                echo "No test"
            fi

or maybe you meant something else?

Cheers,

Sarah

Hi,

Thanks, exactly this. The more logic you’ll need with conditions, the better a script will be.

My preferred way is to move this into a bash script file, as this can get complicated with YAML indents. Also, the bash script can be tested offline, while the YAML cannot be so easily. :slight_smile:

Cheers,
Michael