Golang_demo/docs/sonarqube-fix-guide.md
2025-06-25 17:41:25 +08:00

118 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 🔧 SonarQube Scanner 工具声明修复指南
## 🔍 问题分析
从 Jenkins 错误信息可以看出:
```
Invalid tool type "sonarRunnerInstallation".
Valid tool types: [..., hudson.plugins.sonar.SonarRunnerInstallation, ...]
```
**问题根源**
- ❌ 错误:`sonarRunnerInstallation 'sonarQube'`
- ✅ 正确:需要在 pipeline 中使用`tool`方法动态获取
## ✅ 正确的解决方案
### 方案 1使用 tool 方法(推荐)
```groovy
stage('代码质量扫描') {
steps {
script {
withSonarQubeEnv('sonarQube') {
// 动态获取SonarQube Scanner工具
def scannerHome = tool name: 'sonarQube', type: 'hudson.plugins.sonar.SonarRunnerInstallation'
sh """
${scannerHome}/bin/sonar-scanner \\
-Dsonar.projectKey=\${PROJECT_KEY} \\
-Dsonar.sources=.
"""
}
}
}
}
```
### 方案 2PATH 方式(如果 Scanner 已在 PATH 中)
```groovy
stage('代码质量扫描') {
steps {
script {
withSonarQubeEnv('sonarQube') {
sh '''
sonar-scanner \\
-Dsonar.projectKey=${PROJECT_KEY} \\
-Dsonar.sources=.
'''
}
}
}
}
```
### 方案 3手动路径查找备用方案
```groovy
sh '''
# 查找Scanner路径
SCANNER_PATH=""
for path in \
"/var/jenkins_home/tools/hudson.plugins.sonar.SonarRunnerInstallation/sonarQube/bin/sonar-scanner" \
"$(which sonar-scanner 2>/dev/null)"; do
if [ -f "$path" ]; then
SCANNER_PATH="$path"
break
fi
done
if [ -n "$SCANNER_PATH" ]; then
"$SCANNER_PATH" -Dsonar.projectKey=${PROJECT_KEY}
else
echo "❌ 未找到SonarQube Scanner"
fi
'''
```
## 🎯 最佳实践
1. **不要在 tools 块中声明 SonarQube Scanner**
2. **使用 tool 方法动态获取工具路径**
3. **提供备用方案以提高可靠性**
4. **在环境检查阶段验证工具可用性**
## 🔧 Jenkins 配置要求
确保 Jenkins 中正确配置:
1. **Global Tool Configuration**
```
SonarQube Scanner
├─ 名称: sonarQube
├─ 自动安装: ✅
└─ 版本: SonarQube Scanner 7.1.0.4889
```
2. **System Configuration**
```
SonarQube servers
├─ 名称: sonarQube
├─ 服务器URL: http://your-sonar-server:9000
└─ 认证Token: 配置在Credentials中
```
## 📊 性能优化效果
| 修复前 | 修复后 |
| ------------------ | --------------------------- |
| 语法错误,构建失败 | 构建成功 |
| 无法使用缓存工具 | 使用 Jenkins 管理的缓存工具 |
| 重复下载7 分钟) | 快速启动30 秒) |
通过这个修复,你的 SonarQube Scanner 将正确使用 Jenkins 的工具管理系统,避免重复下载问题。