# GitLab과 SonarQube 연동하기 — sonar-scanner·gitlab-runner 설치부터 Quality Gate까지

> GitLab CI 파이프라인에서 SonarQube 정적 분석을 돌리기까지 필요한 설정을 순서대로 정리한다. SonarQube의 GitLab 연동, project analysis token 발급, gitlab-runner 등록, CI/CD 변수 주입, 그리고 Gradle·JS 프로젝트별 스캐너 설정을 다룬다.

- Source: https://jiny-log.vercel.app/ko/posts/gitlab-sonarqube-integration
- Markdown: https://jiny-log.vercel.app/posts/ko/gitlab-sonarqube-integration.md
- Published: 2025-04-15
- Category: note
- Tags: gitlab, sonarqube, gitlab-ci, devops, docker, quality-gate
- Language: ko

**TL;DR** SonarQube 쪽에서 DevOps Platform Integration으로 GitLab을 등록하고 project analysis token을 만든 뒤, GitLab 프로젝트에 runner를 등록하고 SONAR_HOST_URL·SONAR_TOKEN을 CI/CD 변수로 주입하면 연동이 끝난다. 스캐너 설정은 언어별로 다르다 — JS/TS는 sonar-project.properties, Gradle은 build.gradle의 sonar 블록을 쓴다.

---
## GitLab 에서 토큰 발급

User Settings > Access tokens > `Add new token` 클릭

![GitLab User Settings의 Access tokens 화면. jenkins-token과 sonar-token 두 개의 활성 토큰이 scope와 만료일과 함께 나열되어 있다](/images/gitlab-sonarqube-integration/01.png)


- Token name :: sonar-token
- Select scopes
    - api :: check
    - read_api :: check
    - read_repository :: check

![GitLab의 Add a personal access token 폼. 토큰 이름·설명·만료일 입력란과 api, read_api, read_user 등 scope 체크박스가 보인다](/images/gitlab-sonarqube-integration/02.png)


## GitLab, SonarQube 연동

Administration > Configuration > DevOps Platform Integrations

- `GitLab` > `Create configuration`

![SonarQube Administration의 General Settings > DevOps Platform Integrations 화면. GitHub·Bitbucket·Azure DevOps·GitLab 탭이 있다](/images/gitlab-sonarqube-integration/03.png)


- Configuration name :: GitlabConfiguration
- GitLab API URL :: `${배포된_GitLab_URL}`/api/v4

![SonarQube의 GitLab 설정 편집 폼. Configuration name은 GitlabConfiguration이고 GitLab API URL 입력란의 값은 블러 처리되어 있다](/images/gitlab-sonarqube-integration/04.png)


메인화면 > `Create Proejct` 클릭

- 연결할 GitLab 프로젝트 선택

![SonarQube의 GitLab project onboarding 화면. luna-devops-backend, luna-devops-frontend, luna-frontend-test 세 저장소가 목록에 나온다](/images/gitlab-sonarqube-integration/05.png)


Import 후 메인화면

![SonarQube 프로젝트 목록. luna-devops-backend(Java)와 luna-devops-frontend(TypeScript)가 모두 Quality Gate Passed 상태이고 커버리지는 0.0%로 표시된다](/images/gitlab-sonarqube-integration/06.png)


---

## sonnar scanner 설치

```bash
# 1. 다운로드
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-5.0.1.3006-linux.zip

# 2. 압축 해제
unzip sonar-scanner-cli-5.0.1.3006-linux.zip

# 3. 이동
sudo mv sonar-scanner-5.0.1.3006-linux /opt/sonar-scanner

# 4. 환경변수 설정
echo 'export PATH=$PATH:/opt/sonar-scanner/bin' >> ~/.bashrc
source ~/.bashrc

# (JAVA도 설치되어 있어야 함)
```

---

## GitLab Runner 설치

```bash
# GitLab Runner 저장소 등록
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash

# GitLab Runner 설치
sudo apt-get install gitlab-runner -y
```

### Project runner 발급

- GitLab 접속 후 `${계정}` > `${프로젝트}` > CI/CD Settings > Runners > `New Project runner` 클릭

![GitLab 프로젝트의 CI/CD Settings > Runners 섹션. Project runners와 Instance runners 영역이 나뉘어 있다](/images/gitlab-sonarqube-integration/07.png)


- tags :: `frontend`
- Runner description :: runner-luna-frontend-devops
- `Create runner` 클릭

![GitLab의 New project runner 폼. Tags에 frontend, Runner description에 runner-luna-frontend-devops를 입력한 상태](/images/gitlab-sonarqube-integration/08.png)


### vm에서 runner 등록

프로젝트 > CI/CD Settings > Register runner 화면으로 넘어감

- Platform :: Linux

![GitLab의 Register runner 화면. gitlab-runner register 명령이 표시되며 --url과 --token 값, 그리고 runner authentication token은 블러 처리되어 있다](/images/gitlab-sonarqube-integration/09.png)


위의 명령어 복사해서 터미널에 붙여넣기

```bash
gitlab-runner register  --url http://GITLAB_HOST  --token glrt- ${token_value}
Runtime platform                                    arch=amd64 os=linux pid=142289 revision=ef334dcc version=17.10.1
WARNING: Running in user-mode.                     
WARNING: The user-mode requires you to manually start builds processing: 
WARNING: $ gitlab-runner run                       
WARNING: Use sudo for system-mode:                 
WARNING: $ sudo gitlab-runner...                   
```

- enter
- enter
- shell

```bash
Enter the GitLab instance URL (for example, https://gitlab.com/):
[http://GITLAB_HOST]: http://GITLAB_HOST/
Verifying runner... is valid                        runner=t3_H8jzLk
Enter a name for the runner. This is stored only in the local config.toml file:
[luna-dev-vm]: runner-luna-frontend-devops
Enter an executor: parallels, docker-windows, docker+machine, docker-autoscaler, kubernetes, instance, custom, shell, ssh, virtualbox, docker:
shell
Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded!
 
Configuration (with the authentication token) was saved in "/home/ubuntu/.gitlab-runner/config.toml" 
```

---

## SonarQube token 발급 및 GitLab variables 적용

### sonarqube token 발급

계정 > Security > Generate Tokens

- Name :: gitlab-token-backend
- Type :: Project Analysis Token
- Project :: `${프로젝트이름}`

![SonarQube Administrator의 Security 화면. gitlab-token-backend라는 Project Analysis Token을 발급하는 폼과 기존 토큰 목록이 보인다](/images/gitlab-sonarqube-integration/10.png)


### variables 세팅

luna > `${프로젝트}` > CI/CD Settings

Varables

- Developer :: check
- `Add variable` 클릭

- Visible :: check
- Expand variable reference :: check
- key : SONAR_HOST_URL
- value :: [http://GITLAB_HOST:9002](http://GITLAB_HOST:9002/)

![GitLab CI/CD Settings의 Add variable 패널. Key는 SONAR_HOST_URL, Visibility는 Visible이고 Value는 블러 처리되어 있다](/images/gitlab-sonarqube-integration/11.png)


- Masked :: check
- Expand variable reference :: check
- key : SONAR_HOST_URL
- value :: `${sonar-token-value}`

![GitLab의 Add variable 패널. Key는 SONAR_TOKEN, Visibility는 Masked이고 Value는 블러 처리되어 있다](/images/gitlab-sonarqube-integration/12.png)


### runner 값 적용확인

```bash
cat .gitlab-runner/config.toml
```

```bash
**concurrent = 1
check_interval = 0
connection_max_age = "15m0s"
shutdown_timeout = 0

[session_server]
  session_timeout = 1800

[[runners]]
  name = "luna-dev-vm"
  url = "http://GITLAB_HOST"
  id = 4
  token = "${token_value}"
  token_obtained_at = 2025-04-11T17:08:14Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "shell"
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]

[[runners]]
  name = "luna-dev-vm"
  url = "http://GITLAB_HOST"
  id = 5
  token = "${token_value}"
  token_obtained_at = 2025-04-12T06:22:26Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "shell"
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]**
```

### 아래 경로에 runner 값 재등록

```yaml
sudo vim /etc/gitlab-runner/config.toml
```

- 위의 경로에 runner 값을 재등록 하는 이유

    ## 왜 공식 가이드는 `~/.gitlab-runner/config.toml` 같은 사용자 경로로 설정되는가?

    ### `gitlab-runner`를 "직접 실행"하는 경우

    공식 문서에서는 **Runner를 서비스로 등록하지 않고**,

    `gitlab-runner run`을 **터미널에서 직접 실행**하는 개발 환경 기준 예제가 많음

    ```bash
    gitlab-runner register
    gitlab-runner run
    ```

    이렇게 실행하면, Runner는 **현재 사용자의 홈 디렉토리 (`~/.gitlab-runner/config.toml`)를 사용해서 동작

    ### 하지만 일반적으로는 **서비스로 등록해서 자동 실행**함

    ```bash
    sudo gitlab-runner install
    sudo gitlab-runner start
    ```

    이렇게 하면 Runner는 시스템 서비스(GitLab Runner daemon로 동작하고,

    이 서비스는 항상 `/etc/gitlab-runner/config.toml`을 기본 경로로 삼음

    - 문서에서 로컬 개발/테스트용으로 보여줄 땐 **직접 run  `~/.gitlab-runner/config.toml`**
    - 실무에서는 거의 대부분 **서비스 설치  `/etc/gitlab-runner/config.toml`**

    | 실행 방식 | 설정 파일 위치 | 비고 |
    | --- | --- | --- |
    | `gitlab-runner run` (직접 실행) | `~/.gitlab-runner/config.toml` | 실험용/로컬 테스트 |
    | `systemctl start gitlab-runner` (서비스 실행) | `/etc/gitlab-runner/config.toml` | 실무/자동화 환경  |

    ### 사용하는 설정파일 확인

    - `ps aux | grep gitlab-runner` 실행해서  어떤 설정 파일 쓰는지 확인 가능
    - 서비스 등록된 Runner를 쓰려면  `sudo gitlab-runner register`로 등록해야 `/etc/`에 반영됨

### runner 재시작

```bash
sudo systemctl restart gitlab-runner
```

---

## CI Pipeline Code Example

### frontend

`sonar-project.properties`

```yaml
sonar.projectKey=luna_luna-devops-frontend_00000000-0000-0000-0000-000000000000
sonar.projectName=luna-devops-frontend
sonar.sources=src
#sonar.exclusions=**/node_modules/**,**/*.spec.ts,**/*.test.ts
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.qualitygate.wait=true
```

`.gitlab-ci.yml`

```yaml
stages:
  - build-sonar

build-sonar:
  stage: build-sonar
  tags:
    - sonarqube
  cache:
    policy: pull-push
    key: "sonar-cache-$CI_COMMIT_REF_SLUG"
    paths:
      - "${SONAR_USER_HOME}/cache"
      - sonar-scanner/
  variables:
    JAVA_HOME: "/usr/lib/jvm/java-21-openjdk-amd64"
    PATH: "/opt/sonar-scanner/bin:/usr/lib/jvm/java-21-openjdk-amd64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    SONAR_SCANNER_OPTS: "-Djava.home=/usr/lib/jvm/java-21-openjdk-amd64"

  script:
    - echo "✅ Java 확인"
    - java -version
    - echo "✅ SonarScanner 버전"
    - sonar-scanner -v
    - echo "✅ sonar-project.properties 내용 확인"
    - cat sonar-project.properties
    - echo "✅ sonar-scanner 실행"
    - sonar-scanner -Dsonar.host.url="$SONAR_HOST_URL" -Dsonar.login="$SONAR_TOKEN" -X

  allow_failure: true
  rules:
#    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
    - if: $CI_COMMIT_BRANCH == 'main'
```

### backend

`build.gradle.kts (luna-devops-backend)`

```yaml
plugins {
    id("org.springframework.boot") version "3.2.2"
    id("io.spring.dependency-management") version "1.1.4"
    id("java")
    id ("org.sonarqube") version "6.0.1.5171"
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    // **Spring Boot 기본 웹 기능 (REST API 개발)**
    implementation("org.springframework.boot:spring-boot-starter-web")

    // **JPA + Hibernate (데이터베이스 연동)**
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")

    // **H2 데이터베이스 (In-Memory DB)**
    runtimeOnly("com.h2database:h2")

    // **Lombok (Getter, Setter, 생성자 자동 생성)**
    compileOnly("org.projectlombok:lombok")
    annotationProcessor("org.projectlombok:lombok")

    // **Spring Boot 테스트 (JUnit 포함)**
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation(platform("org.junit:junit-bom:5.10.0"))
    testImplementation("org.junit.jupiter:junit-jupiter")
}

tasks.test {
    useJUnitPlatform()
}

sonar {
    properties {
        property("sonar.projectKey", "luna_luna-devops-backend_00000000-0000-0000-0000-000000000000")
        property("sonar.projectName", "luna-devops-backend")
        property("sonar.qualitygate.wait", true)
    }
}

// ✅ SonarQube 실행 전에 테스트 자동 실행되게 설정 (선택)
tasks.named("sonarqube") {
    dependsOn("test")
}
```

`.gitlab-ci.yml`

```yaml
stages:
  - build-sonar

build-sonar:
  stage: build-sonar
  tags:
    - sonarqube  # 해당 태그 가진 Runner가 있어야 함!
  cache:
    policy: pull-push
    key: "sonar-cache-$CI_COMMIT_REF_SLUG"
    paths:
      - "${SONAR_USER_HOME}/cache"
      - .gradle/
  variables:
    JAVA_HOME: "/usr/lib/jvm/java-21-openjdk-amd64"
    PATH: "/opt/sonar-scanner/bin:/usr/lib/jvm/java-21-openjdk-amd64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    SONAR_SCANNER_OPTS: "-Djava.home=/usr/lib/jvm/java-21-openjdk-amd64"
    GRADLE_OPTS: "-Dorg.gradle.daemon=false"

  script:
    - echo "✅ Java 확인"
    - java -version
    - echo "✅ Gradle 테스트 실행"
    - ./gradlew test
    - echo "✅ SonarQube 분석 시작"
    - ./gradlew sonarqube -Dsonar.host.url="$SONAR_HOST_URL" -Dsonar.login="$SONAR_TOKEN"

  allow_failure: true
  rules:
    - if: $CI_COMMIT_BRANCH == 'main'

```