在 Gitlab CI 中調用 Sonarqube 進行代碼掃描

Gitlab 提供了基於 Code Climate 的代碼質量評估功能,這一功能是通過 dind(Docker in Docker)方式運行的,在 Kubernetes 環境中、尤其是託管集群中,這種方式不太合適,還好還有一個替代方案:Sonarqube,通過在 .gitlab-ci.yml 中的設置,可以使用 Sonarqube 對代碼進行掃描,接收到 Commit 之後,Sonarqube 會生成針對提交的代碼質量提示,如圖所示:

在 Gitlab CI 中調用 Sonarqube 進行代碼掃描

Show

過程也並不複雜,簡單的部署一個 Sonarqube 服務,並在 Gitlab CI 中調用即可。

配置 Gitlab

這個步驟很簡單,只要打開頁面 profile/personal_access_tokens,新建 Token 備用即可。

啟動 Sonarqube

在 Kubernetes 環境中啟用一個簡單的 Sonarqube 服務器是很方便的,具體說明可以參看官方 Docker 鏡像的說明,這裡有幾個重點:

  1. 數據:該鏡像內置 H2 存儲,在生產環境中使用自然是不合適的,可以通過環境變量,使用外部的 MySQL 或者 PostgreSQL 服務器。
  2. 持久化:該鏡像的數據目錄為 /opt/sonarqube/,下面的 data、logs、conf 和 extensions,都是需要接入 PVC 進行持久化存儲的。(就算只是測試,因為安裝插件需要重啟,因此也需要提供持久化支持)
  3. 權限:該鏡像主進程是使用 999 的組 ID 運行的,因此需要進行配置。
  4. 後續內容所用插件目前還無法支持 Sonarqube 7.7,因此此處使用的是 7.6 版本。

總結以上幾點,列出代碼中需要注意的內容:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: sonarqube
labels:
app: sonarqube
spec:
...
template:
metadata:
...
spec:
securityContext:
fsGroup: 999
containers:
- name: sonarqube
image: "sonarqube:7.6-community"
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 9000
volumeMounts:
- name: sonar-ext
mountPath: /opt/sonarqube/extensions
- name: sonar-data
mountPath: /opt/sonarqube/data
- name: sonar-log
mountPath: /opt/sonarqube/logs
- name: sonar-conf
mountPath: /opt/sonarqube/conf
...

配置 Sonarqube

Sonarqube 啟動之後,使用缺省用戶名和密碼(admin/admin)登錄之後,首先安裝 Java 語言插件:

  • 在 /account/security/ 修改密碼。
  • 前往 /admin/marketplace 安裝 SonarJava 插件。
  • 打開路徑 /admin/system,重啟服務。

接下來是手工安裝 Gitlab 插件:

  • 使用 kubectl exec -it 進入 Sonarqube 的 Pod 中。
  • 進入 /opt/sonarqube/extensions/plugins 路徑,下載插件
  • 重啟 Sonarqube。

插件安裝完成之後,/projects/create 創建新項目,選擇 java -> maven,最終會出現如下提示:

在 Gitlab CI 中調用 Sonarqube 進行代碼掃描

新建項目

其中包含了後續步驟所需要的 Token。

配置 Gitlab 插件

  • 打開 admin/settings?category=gitlab。
  • 填寫 GitLab url 以及 GitLab User Token。
  • 保存。

配置項目 CI

這部分相當簡單的一行 Maven 命令,例如

stages:
- test
- scan
...
Sonar:
stage: scan
tags:
- maven
/> - mvn --batch-mode verify sonar:sonar -Dsonar.host.url=https://sonar.microservice.xyz -Dsonar.login=cd387c80d1d40b24c1000b9982778ecef572795c -Dsonar.projectKey=sam -Dsonar.gitlab.project_id=$CI_PROJECT_ID -Dsonar.gitlab.commit_sha=$CI_COMMIT_SHA -Dsonar.gitlab.ref_name=$CI_COMMIT_REF_NAME

這裡的關鍵參數:

  • sonar.host.url:Sonarqube 的地址。
  • sonar.login:Sonarqube 配置新項目時生成的 Token
  • sonar.projectKey:Sonarqube 新項目生成的 ID。

完成上述修改之後,就可以提交你的 Java 代碼,看看 Sonarqube 在 Commit 下使用評論方式發表的代碼分析結果。

附錄

  • 插件項目地址:https://github.com/gabrie-allaigre/sonar-gitlab-plugin/


分享到:


相關文章: