How deploy your application just on successful stage(s) on GitLab CI

I’m not very proficient with GitLab CI/CD/Pipelines, and I have been trying to automate deployment only when a specific stage is successful, in my case, the test stage. I attempted to use global variables, but it seems that they cannot be reassigned within one job and used in another job. After researching on GitLab Docs [1] and Stack Overflow [2], I found a solution that works for me.

Below is the structure of my .gitlab-ci.yml file:

stages:
  - build
  - test
  - deploy

build:
  stage: build
  script:
    - mvn -DskipTests package

test:
  stage: test
  script:
    - echo "Executing the tests..."
    - mvn test
  after_script:
    - echo $CI_JOB_STATUS >> ./results.txt
  artifacts:
    paths:
      - results.txt

deploy:
  stage: deploy
  script:
    - echo "Checking if tests are successful..."
    - cat results.txt | if [[ "$(cat)" == *"success"* ]]; then
      echo "Okay! now I should do the deploy";
      else
      echo "Ops, there are test failing";
      fi
  dependencies:
    - test

We’re using artifacts and dependencies to pass information from the earlier stage (test) to the deploy stage.

You can check the results.txt file for the status of ‘success,’ ‘failed,’ or ‘canceled.’ Additionally, you can include other predefined variables [3] and informations.

If you’re using Windows, remember to save the .gitlab-ci.yml file with LF (line separator \n) to avoid any problems when running the script.

If you are aware of a better approach for accomplishing this task, please feel free to share it with me.

References:

  1. https://docs.gitlab.com/ee/ci/yaml/
  2. https://stackoverflow.com/questions/38140996/how-can-i-pass-gitlab-artifacts-to-another-stage
  3. https://docs.gitlab.com/ee/ci/variables/predefined_variables.html