Jenkins Pipline使用SonarScanner中遇到的Bug

在Jenkins上使用Pipline进行集成,利用SonarScanner做静态代码扫描的过程中,遇到了几个问题,这里记录了一点解决办法。

1.脚本变量定义错误:
  自动安装SonarScanner插件,在Pipline脚本中使用官方wiki中说明的脚本:

 stage('SonarQube analysis') {
    // requires SonarQube Scanner 2.8+
    def scannerHome = tool 'SonarQube Scanner 2.8';
    withSonarQubeEnv('My SonarQube Server') {
      sh "${scannerHome}/bin/sonar-scanner"
    }
  }

  但是在扫描的时候总是报错,可以看出是语法错误:

WorkflowScript: 33: Not a valid stage section definition: "def sonarqubeScannerHome = 'SonarQubeScanner2.8'". Some extra configuration is required. @ line 33, column 9.
           stage('SonarQubeanalysis') {
           ^
WorkflowScript: 33: Unknown stage section "withSonarQubeEnv". Starting with version 0.5, steps in a stage must be in a steps block. @ line 33, column 9.
           stage('SonarQubeanalysis') {
           ^
WorkflowScript: 33: No "steps" or "parallel" to execute within stage "SonarQubeanalysis" @ line 33, column 9.
           stage('SonarQubeanalysis') {
           ^  

  因为在stage里面不是用def来定义变量的,于是尝试将变量定义放在脚本里,问题得到了解决:

stage('SonarQubeanalysis') {
            steps{
                script {
                    scannerHome = tool 'SonarQubeScanner2.8'
                    //这里这个tool是直接根据名称,获取自动安装的插件的路径
                }
            withSonarQubeEnv('SonarQube') {
                sh "${scannerHome}/bin/sonar-scanner sonar.projectKey=YourProjectKey sonar.sources=."
            }
            }
        }

2.变量引用错误:
  在修改成上面的脚本后,运行再次报错,找不到sonar.sources这个选项:

/yourpath/tools/hudson.plugins.sonar.SonarRunnerInstallation/SonarQubeScanner2.8/bin/sonar-scanner sonar.projectKey=YourProjectKey sonar.source=.
ERROR: Unrecognized option: sonar.source=.
INFO: 
INFO: usage: sonar-scanner [options]
INFO: 
INFO: Options:
INFO:  -D,--define <arg>     Define property
INFO:  -h,--help             Display help information
INFO:  -v,--version          Display version information
INFO:  -X,--debug            Produce execution debug output
INFO:  -i,--interactive      Run interactively

  经过大神指导,发现在运行SonarScanner的时候,需要用‘-D’来标记(如果这两个参数是写在sonar-scanner.properties里就不需要了):

stage('SonarQubeanalysis') {
            steps{
                script {
                    scannerHome = tool 'SonarQubeScanner2.8'
                }
            withSonarQubeEnv('SonarQube') {
                sh "${scannerHome}/bin/sonar-scanner -Dsonar.projectKey=YourProjectKey -Dsonar.sources=."
            }
            }
        }

3.登录受限:
  在上面的问题都解决了之后,发现登录所需要属性错误:

ERROR: Error during SonarQube Scanner execution
ERROR: Not authorized. Please check the properties sonar.login and sonar.password.
ERROR: 
ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.

  出现这个bug的时候,用的是SonarQube5.2版本,所以需要Jenkins通过账户密码登录,但是因为账号权限受限,所以无法连接到Sonar的服务器,所以后来更新账号密码就好了。

    原文作者:M_GBO
    原文地址: https://www.jianshu.com/p/50a824ef7afb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞