Allowing failure in GitLab CI

Jun 20, 2024·
Gert de Pagter
Gert de Pagter
· 2 min read

In GitLab, sometimes you want to (temporarily) allow a script to fail. It may be that you are running your tests against a newer PHP/NodeJs version, which you are not yet compatible with. In that case you can allow the pipeline to fail, without blocking anything else, or turning it red and blocking your merges. As mentioned in a previous post, you shouldn’t be abusing it, but sometimes you may need to allow a failure.

Allow a step to fail

Let’s say you have this phpunit step for a new PHP version. If you want this whole step to be allowed to fail, just add allow_failure: true to the yaml.

phpunit_85:
    image: php:8.5-cli
    stage: test
    script:
      - ./bin/setup_environment.sh
      - vendor/bin/phpunit
phpunit_85:
    image: php:8.5-cli
    stage: test
    script:
      - ./bin/setup_environment.sh
      - vendor/bin/phpunit
    allow_failure: true

Allow a single part of the script to fail

However, sometimes a part of the script can fail, but you would still want the other parts to succeed. If we take a look at the previous example, we may allow ./bin/setup_environment.sh to fail, but require phpunit to pass. This could be the case if we are using a template, and the setup_environment.sh file may not exist. In that case we can add || true after the command. This causes that line of shell code to pass, even if it has an error. What it does is if the command to the left of the || fails, it tries the next one, which is true. And the true command does nothing but exit successfully.

Which would look like this:

phpunit_85:
    image: php:8.5-cli
    stage: test
    script:
      - ./bin/setup_environment.sh || true
      - vendor/bin/phpunit

With these 2 possibilities you can allow your GitLab CI pipelines to fail, while you are working on a solution. This generally shouldn’t be a permanent solution, but rather a temporary one to fix your problems.

If you want to get notified of the next blog post, join the newsletter.