Search code examples
bashgitlabcode-coveragegitlab-ci-runnercicd

Gitlab CI/CD - sending comments/alerts to the gitlab UI?


Currently I have this line in my .gitlab-ci.yml file:

if (( $coverage < $MIN_COVERAGE )) ; then echo "$coverage% of code coverage below threshold of $MIN_COVERAGE%" && exit 1 ; else exit 0 ; fi

$coverage is the test coverage of the code, determined with pytest-cov

$MIN_COVERAGE is a specified minimum level of test coverage which $coverage shouldn't drop below

Currently, this causes the pipeline to fail if, for instance, coverage is 70% and min_coverage is 80%. A message is also printed to the terminal: "$coverage% of code coverage below threshold of $MIN_COVERAGE%"

However, this message is only displayed in the terminal of the gitlab job, so if someone wanted to see why and by how much their pipeline failed they would need to go into the job terminal and look at the output.

Instead of having this echo to the job terminal, is there a way to get this message to output somewhere on the gitlab UI?


Solution

  • Here's how to create a new Merge Request Note/Comment using the GitLab API.

      script:
        # Project -> Settings -> Access Tokens, Create token with API scope.
        # Project -> Settings -> CI/CD -> Variables, Store as CI_API_TOKEN
        # GET /merge_requests?scope=all&state=opened&source_branch=:branch_name
        - |
          merge_request_iid=$( \
            curl --request GET \
              --header "PRIVATE-TOKEN: ${CI_API_TOKEN}" \
              "${CI_API_V4_URL}/merge_requests?scope=all&state=opened&source_branch=${CI_COMMIT_REF_NAME}" | \
            jq .[0].iid \
          )
        # POST /projects/:id/merge_requests/:iid/notes
        - json_data='{"body":"Your message, here"}'
        - |
          echo $json_data |
          curl --request POST \
            --header "PRIVATE-TOKEN: ${CI_API_TOKEN}" \
            --header "Content-Type: application/json" \
            --data @- \
            "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${merge_request_iid}/notes"