北屋教程网

专注编程知识分享,从入门到精通的编程学习平台

Jenkins运维之路(Sonarq接入)_jenkins poll scm

接入Sonarq对代码进行扫码,一般的情况下感觉用不上代码扫描。不过现在好像都流行要结合一下,那我也就结合下

1.安装必要插件

image-20250918104628445

image-20250918104722621

2. Sonarq服务器配置2.1 创建token(用于jenkins连接Sonarq使用)

image-20250918105231621

2.2 创建主动回调

项目分析完成后通知外部服务。系统会向你提供的每个网址发送一个带有 JSON 数据的 HTTP POST 请求,这里在后面jenkins获得代码扫描结果又作用

image-20250918105656510

2.3 调整SCM

image-20250918105930580

3.配置Jenkins连接Sonarq服务器及SonarqCLI

3.1 添加Sonarq密钥

Jenkins-->系统管理-->凭据管理-->Stores scoped to Jenkins-->全局-->Add Credentials

image-20250918110435637

3.2 添加Sonarq服务器

image-20250918110552282

3.3 添加Sonarq客户端

image-20250918110637435

3.4 Sonarq客户端配置

[root@CICDRunner-47 sonar-scanner-5.0.1]# cat conf/sonar-scanner.properties
#----- Default SonarQube server
sonar.host.url=https://sonar.xxxxxx.top

#----- Default source code encoding
sonar.sourceEncoding=UTF-8

4. Sonarq Pipeline

        stage("SonarQube Analysis") {
            steps {
                script {
                    // 获取 sonar-scanner 工具路径
                    def sonarqubeScanner = tool name: 'SonarScanner501'
                    
                    withSonarQubeEnv('SonarqubeServ13') { // 使用 SonarQube 服务器名称
                        withCredentials([string(credentialsId: 'Jenkins-SonarqubeServ', variable: 'SONAR_AUTH_TOKEN')]) {
                            sh """
                            ${sonarqubeScanner}/bin/sonar-scanner \
                                -Dsonar.projectKey=${JOB_NAME} \
                                -Dsonar.projectName=${JOB_NAME} \
                                -Dsonar.sources=src \
                                -Dsonar.java.binaries=target/classes \
                                -Dsonar.host.url=$SONAR_HOST_URL \
                                -Dsonar.login=$SONAR_AUTH_TOKEN 
                            """
                        }
                    }
                }
            }
        }
        stage("Quality Gate") {
            steps {
                timeout(time: 20, unit: 'MINUTES') {
                    script { // 使用 script 块来包裹 Groovy 代码
                        def qg = waitForQualityGate() // 等待 SonarQube 的质量门结果
                        if (qg.status != 'OK') { // 检查质量门的状态
                            error "Pipeline aborted due to quality gate failure: ${qg.status}" // 中止流水线
                        }
                    }
                }
            }
        }
        stage('Wait for SonarQube Analysis') {
            steps {
                script {
                    // 使用 SonarQube 服务器名称和凭据
                    withSonarQubeEnv('SonarqubeServ13') {
                        withCredentials([string(credentialsId: 'Jenkins-SonarqubeServ', variable: 'SONAR_AUTH_TOKEN')]) {
                            // 等待 SonarQube 分析完成
                            timeout(time: 10, unit: 'MINUTES') {
                                waitUntil {
                                    // 查询 SonarQube 分析状态
                                    def curlCommand = "curl -s -u \$SONAR_AUTH_TOKEN: \$SONAR_HOST_URL/api/project_analyses/        search?project=\$JOB_NAME"
                                    def response = sh(script: curlCommand, returnStdout: true).trim()
                                    def exitCode = sh(script: curlCommand, returnStatus: true)
        
                                    // 打印响应以进行调试
                                    echo "Response from SonarQube: ${response}"
        
                                    // 检查返回状态
                                    if (exitCode != 0) {
                                        error("Curl command failed with exit code: ${exitCode}. Response: ${response}")
                                    }
        
                                    // 检查响应是否为有效的 JSON 字符串
                                    if (response) {
                                        try {
                                            // 解析 JSON 响应
                                            def jsonResponse = readJSON(text: response)
                                            
                                            // 检查分析结果
                                            if (jsonResponse.analyses && jsonResponse.analyses.size() > 0) {
                                                // 获取最新的分析
                                                def latestAnalysis = jsonResponse.analyses[0]
                                                echo "Latest Analysis Key: ${latestAnalysis.key}, Date: ${latestAnalysis.date}"
        
                                                // 这里可以根据需要检查分析状态
                                                // 假设我们需要检查某个特定的条件,比如是否有事件
                                                if (latestAnalysis.events.size() > 0) {
                                                    echo "New events found in analysis."
                                                    // 可以在这里处理事件
                                                } else {
                                                    echo "No new events found in analysis."
                                                }
        
                                                // 如果您需要根据分析的其他条件决定成功与否,可以在这里进行判断
                                                return true // 或者根据条件返回 true/false
                                            } else {
                                                error("No analyses found in the response.")
                                            }
                                        } catch (Exception e) {
                                            error("Failed to parse JSON response: ${e.message}. Response: ${response}")
                                        }
                                    } else {
                                        error("Received empty response from SonarQube.")
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

image-20250918111651947

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言