Sonarqube系列05:GitLab 集成实践

Sonarqube 支持与 GitLab 集成以提供一系列自动化交互功能,包括集成 Gitlab 登录、GitLab 项目导入及 Merge Request 评论联动。

本篇重点介绍如何配置集成以上功能。

1. 前置条件

  • 已本地部署的 GitLab
  • 具备相应项目权限的 GitLab 账号
  • GitLab 版本>11.7

2. GitLab 登录

GitLab 支持创建 Application,提供身份验证、用户资料读取、仓库读取等功能,用于与三方平台对接,而 Sonarqube 社区版本默认实现了 GitLab 身份验证功能。
主要配置工作如下:

  • GitLab 配置
    • 创建集成的 Application
  • Sonarqube 配置
    • 配置访问地址
    • 配置 Gitlab 验证信息( Application 的 ID 和 Secret )

2.1. GitLab 配置

2.1.1. 创建集成的 Application

登录 GitLab 后,按如下步骤创建登录应用。

  1. In the top-right corner, select your avatar.
  2. Select Settings.
  3. On the left sidebar, select Applications.
  4. Enter a NameRedirect URI, select Scopes.
    • Name : sonarqube-login.
    • Redirect URI : Enter your SonarQube URL with the path /oauth2/callback/gitlab. For example, https://sonarqube.mycompany.com/oauth2/callback/gitlab.
    • Scopes : Select api if you plan to enable group synchronization. Select read_user if you only plan to delegate authentication.
  5. Select Save application.
    保存后记录展示的 Application ID 和 Secret

2.2. Sonarqube 配置

2.2.1. 配置访问地址

进入 Administration > Configuration > General Settings > General

  • Server base URL : GitLab 可访问的 Sonarqube 局域网/公网基础 URL,需与 GitLab Application Redirect URI 前缀一致,例如,之前填的是 https://sonarqube.mycompany.com/oauth2/callback/gitlab,这里需要填 https://sonarqube.mycompany.com,否则 GitLab 登录回调会不成功。

2.2.2. 配置 GitLab 验证信息

进入 Administration > Configuration > General Settings > ALM Integrations > GitLab > Authentication

  • Enabled : set to true.
  • Application ID : GitLab Application ID.
  • Secret : GitLab Application Secret.

3. GitLab 联动

除基础的集成 GitLab 登录之外,Sonarqube 还支持通过 GitLab 开放 API 进行交互,实现 GitLab 项目导入及 Merge Request 评论联动。

3.1. GitLab 配置

3.1.1. 创建账户 Access Token

  1. In the top-right corner, select your avatar.
  2. Select Settings.
  3. On the left sidebar, select Access Tokens.
  4. Enter a NameExpires at, select Scopes.
    • Name : Personal access token name.
    • Expires at : Expire date.
    • Scopes : Select api.

3.2. Sonarqube 配置

3.2.1. GitLab 联动配置

进入 Administration > General Settings > ALM Integrations > GitLab

  • Configuration name : Configuration name for display
  • GitLab API URL : Check in this your-gitlab-domain/help/api/README.md. For GitLab 13.x.x is your-gitlab-domain/api/v4
  • Personal Access token : GitLab account access token

配置完成后 New Project 支持下拉选择 GitLab 跳转到 GitLab 项目列表页选择对应的项目,Sonarqube 会自动创建与之关联的项目。

3.2.2. 手动关联项目

除了采用上面的方式导入的 GitLab 项目实现关联外,对于已存在的项目可以手动进行关联:
进入 Project Settings > General Settings > Pull Request Decoration

  • Configuration name : The configuration name that corresponds to your GitLab instance
  • Project ID : Your GitLab Project ID found in GitLab

4. 参考资料