Redundant .gitlab-ci.yml file

I am new to Gitlab and Gitlab CI and I am reading the documentation for .gitlab-ci.yml files. I was looking through some of the examples and from my knowledge this yml seems to be cleaning up the build twice when the build fails. I would appreciate any help with explaining what this file is doing. Thank you in advance to all the help.

stages:
- build
- cleanup_build
- test
- deploy
- cleanup

build_job:
  stage: build
  script:
  - make build

cleanup_build_job:
  stage: cleanup_build
  script:
  - cleanup build when failed
  when: on_failure

test_job:
  stage: test
  script:
  - make test

deploy_job:
  stage: deploy
  script:
  - make deploy

cleanup_job:
  stage: cleanup
  script:
  - cleanup after builds
  when: always

Well, I’m not an expert, but it looks to me like you have asked it to do two cleanups…

The first one occurs only when a build fails:

cleanup_build_job:
    stage: cleanup_build
    script:
    - cleanup build when failed
    when: on_failure  # <-- Do first cleanup on failure

And the second one occurs at the end for all builds:

cleanup_job:
    stage: cleanup
    script:
    - cleanup after builds
    when: always  # <-- Do more cleanup at the end of every build

If the scripts in those 2 jobs do similar things, it might seem like redundant actions are occurring. I would suggest that your failure script that runs during cleanup_build_job should not duplicate the actions of the generic cleanup script (during cleanup_job). Rather, the failure script should only do things specific to a failed build.