Skip to main content

Command Palette

Search for a command to run...

GitLab CI/CD và kiểm định chất lượng code với SonarCloud (P.2)

Published
2 min read

Hello! I'm Zu.Doan

Sau khi đọc xong phần 1 về Gitlab CI/CD chắc hẳn các bạn đã tạo được một CI/CD job đơn giản để áp dụng cho dự án của mình rồi đúng không.

Tiếp tục sang phần 2 này mình sẽ hướng dẫn các bạn tích hợp SonarCloud để kiểm tra chất lượng code.

Trong file gitlab-ci.yaml chúng ta sẽ chỉnh sửa như sau

  • Ở khu phần stages chúng ta sẽ thêm một step nữa tên là review
stages:
  - build
  - test
  - review // <= thêm mi dòng này
  • Tiếp theo tương ứng với step review đó, ta sẽ viết các script tương ứng như sau
review:
  stage: review
  variables:
    SONAR_USER_HOME: '${CI_PROJECT_DIR}/.sonar' # Defines the location of the analysis task cache
    GIT_DEPTH: '0' # Tells git to fetch all the branches of the project, required by the analysis task
  image:
    name: sonarsource/sonar-scanner-cli:latest
    entrypoint: ['']
  cache:
    key: '${CI_JOB_NAME}'
    paths:
    - .sonar/cache
  script:
    - sonar-scanner

Để biết làm sao chúng ta có đoạn code cho review step, các bạn vui lòng tham khảo bài viết Cách thiết lập SonarCloud cho một Gitlab repository.

Kết quả cuối cùng ta sẽ được file gitlab-ci.yaml như sau:

image: docker/compose:alpine-1.27.4

services:
  - docker:dind

stages:
  - build
  - test
  - review

build:
  stage: build
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    - docker pull $CI_REGISTRY_IMAGE:latest || true
    - docker build --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA

test:
  stage: test
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:latest
  script:
    - docker run -d --name api-shops $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - sleep 15
    - docker exec api-shops sh -c "npm run test"
  coverage: /All files[^|]*\|[^|]*\s+([\d\.]+)/I

review:
  stage: review
  variables:
    SONAR_USER_HOME: '${CI_PROJECT_DIR}/.sonar' # Defines the location of the analysis task cache
    GIT_DEPTH: '0' # Tells git to fetch all the branches of the project, required by the analysis task
  image:
    name: sonarsource/sonar-scanner-cli:latest
    entrypoint: ['']
  cache:
    key: '${CI_JOB_NAME}'
    paths:
    - .sonar/cache
  script:
    - sonar-scanner

Sau đó các bạn có thể push commit lên repository để kiểm tra xem pipeline đã chạy chưa nhé.

Trong phần tiếp theo, mình sẽ viết về cách push docker image mới tương ứng với code mới lên registry container thông qua quá trình CI/CD.

Hi vọng bài viết này hữu ích với các bạn.

Thank everyone! Bye2 :D

More from this blog

zujs

35 posts