SonarQube 集成 GitLabCI


本文是用於分析SonarQube代碼的質量,每次在GitLab上提交代碼時都使用GitLab-CI運行器進行檢查。

1.SonarQube with GitLab

安裝插件GitLab-plugin for SonarQube,轉到Adminstration-> MarketPlace,搜索“GitLab”,然后單擊安裝,安裝完成后,重新啟動SonarQube


為SonarQube設置GitLab插件:從GitLab獲取用戶令牌。


轉到SonarQube:管理 - >配置 - > GitLab:

GitLab url: add your GitLab url

GitLab User Token: 上一步獲取的token

2.Sonar Scanner


您需要一個sonar scanner來掃描您的代碼。根據官方文檔,SonarQube Scanner被推薦為使用SonarQube分析項目的默認啟動器。下載sonar scanner for msbuilder,.net 跟 .net core 都有對應的版本,

這里我們下載.net 的版本(為何不使用.net core,.net core 版本執行shell命令涉及到了一些權限問題,暫時沒有找到解決方案),解壓縮:

編輯SonarQube.Analysis.xml,修改sonar平台地址,以及用戶名密碼:

GitLab-CI Runner

我們需要GitLab-CI Runner來幫助我們運行作業並將結果發送回GitLab。 
a.在系統中的某個位置創建一個文件夾,例如:C:\ GitLab-Runner。 
b.下載x86或amd64的二進制文件並將其放入創建的文件夾中。將二進制文件重命名為gitlab-runner.exe,如下是gitlab runner文件夾

 

 c.運行管理員命令提示符。

 d.通過cmd:“gitlab-runner.exe register”注冊Runner,輸入它一步一步詢問的信息。 

    d1. GitLab Url  

    d2. 令牌:在CI / CD設置頁面中獲得的。

 

 

 d3.描述:跑步者的描述 
 d4.標簽:與Runner相關聯的標簽,可以稍后在GitLab的UI中進行更改。 
 d5.Runner執行者:eg.shell,docker等。 
e.將Runner作為服務安裝並啟動它。 (使用內置系統或用戶帳戶運行服務)
 e1. cmd:gitlab-runner install 
 e2. cmd:gitlab-runner start

 

f. 編寫.gitlab-ci.yml並將其放在GitLab上的根目錄下,當存儲庫發生任何更改時,它將運行這個腳本。

stages:
     - publish
 
Sonar_Publish:
     stage: publish
     script:
         - chcp  65001
         - dotNetSonarDemo\sonar_runner.bat
     only:
         - master

編寫bat腳本文件:

@ECHO off
 
CALL :build
GOTO:eof
 
:build
FOR   /r   %%L IN (*.sln) DO (
echo  Doing  %%L ...........
call  "d:\sonarms\MSBuild.SonarQube.Runner.exe"  begin  /k : "%%~nL"  /v : "1.0"  /d :sonar.analysis.mode=publish  /d :sonar.gitlab.commit_sha=%CI_COMMIT_SHA%  /d :sonar.gitlab.project_id=%CI_PROJECT_ID%  /d :sonar.gitlab.ref_name=%CI_COMMIT_REF_NAME%  /d :sonar.cs.opencover.reportsPaths= "%%~pL%%~nLTest\projectCoverageReport.xml"
call  "E:\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"  %%L
call  "d:\sonarms\MSBuild.SonarQube.Runner.exe"  end
)

修改本地代碼並推送,查看gitlab自動構建信息如下:

job執行成功,sonar平台上也能查看到掃描記錄:

分割線------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

sonar 集成gitlab 掃描.net core 出現的問題:

running the scanner for msbuild under local system or network service account is not supported

好多老外也遇到了這個問題:https://github.com/SonarSource/sonar-scanner-msbuild/issues/522,不知道有沒有什么好的方式,誰能幫我?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM