Получить значение из сценария powershell в файле jenkins - PullRequest
0 голосов
/ 16 октября 2019

Я пытаюсь извлечь строку из скрипта powershell и использовать ее в файле Jenkins, чтобы изменить отображаемую версию в SonarQube.

Я начал реализовывать функциональность для взятия версии проекта с package.json,В основном, я даю каталог Workspace в качестве параметра и спрашиваю полный путь, если он находит package.json в Workspace сам по себе или в дочерних папках. Если файл найден, проанализируйте его и верните версию:

updateDisplayedVersionInSonar.ps1

param (
  [Parameter(Mandatory = $true)]
  [string]$Workspace
)
try{

    $packageFullPath = ""
    $pcgVersion = ""

    Get-ChildItem -Path ${Workspace} -Filter package.json
     -Recurse -ErrorAction SilentlyContinue -Force | % {$packageFullPath = $_.FullName}
    try { 

      Test-Path $packageFullPath -PathType leaf

      $json = Get-Content $packageFullPath | Out-String | ConvertFrom-Json

      if($json.PSobject.Properties.Name -contains "version"){       
        $pcgVersion =  $json.version
      }
      else{
        $pcgVersion = "unknown"
      }

      Write-Output $pcgVersion          
  }
  catch {
    Write-Output "There is no package.json file!"
  }
}
catch{
  $ErrorMessage = $_.Exception.Message
  write-host "An error has occured: ${ErrorMessage}"
  exit 1
}

Теперь я хочу использовать версию, возвращенную из сценария ps в Jenkinsfile:

stage('SonarQube Frontend') {
environment {
    sonarqubeScannerHome = tool name: 'SonarQube Scanner', type: hudson.plugins.sonar.SonarRunnerInstallation'
    sonarQubeId = 'SonarQubeServer'
    sonarProjectName = "\"SPACE ${REPOSITORY_NAME}\""
    sonarProjectKey = "${REPOSITORY_NAME}"
    testsPaths = 'app/myProject-ui/webapp/TEST/unit/utils'
    testExecutionReportPaths = 'app/myProject-ui/reports/sonar/TESTS-qunit.xml'
    javascriptLcovReportPaths = 'app/myProject-ui/reports/coverage/lcov.info'
}
steps {

    withSonarQubeEnv(env.sonarQubeId) {     
        withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: sonarQubeId, usernameVariable: 'SONAR_USER', passwordVariable: 'SONAR_PASSWORD']]) {   
            script{
                sonarProperties =  " -Dsonar.projectName=${env.sonarProjectName}" +
                    " -Dsonar.projectKey=${env.sonarProjectKey}" +   
                    " -Dsonar.login=${SONAR_USER}" +
                    " -Dsonar.password=${SONAR_PASSWORD}" +
                    " -Dsonar.sources=./" +  
                    " -Dsonar.exclusions=**/*.java"
                //some other conditions

                //this line will be executed and i will see in Jenkins Console output the version found in package.json
                powershell "powershell -File C:/Automation/updateDisplayedVersionInSonar.ps1 -Workspace '${env.WORKSPACE}/app'"

                //I try to make it as a variable, but it will print "echo version here - null -" :(
                pcgVersion = powershell "powershell -File C:/Automation/updateDisplayedVersionInSonar.ps1 -Workspace '${env.WORKSPACE}/app'" 
                echo "echo version here - ${pcgVersion} -"

                //I want to use it here in order to be displayed the correct version of the app in Sonar
                sonarProperties = sonarProperties + " -Dsonar.projectVersion= ${pcgVersion}" 
            }

        bat "${env.sonarqubeScannerHome}/bin/sonar-scanner" + " -Dsonar.host.url=${SONAR_HOST_URL}" + sonarProperties
        }   

    } 
}
} //end of SonarQube Frontend stage

Я попробовал решение из Как выполнить сценарий powershell от jenkins, передав параметры , но безрезультатно.

Я попытался также сделать это:

version = powershell(returnStdout: true, script:'powershell -File C:/SCP/Automation/updateDisplayedVersionInSonar.ps1 -Workspace "${env.WORKSPACE}"')


version = powershell(returnStdout: true, script:'C:/SCP/Automation/updateDisplayedVersionInSonar.ps1 -Workspace "${env.WORKSPACE}"')

Я нашел довольно много примеров того, как использовать переменную Jenkins в Powershell, но не наоборот: (

Что я делаю неправильно? Этого можно добиться?

Спасибо!

1 Ответ

1 голос
/ 16 октября 2019

Вместо этого вы можете использовать Jenkins Pipeline Utility .

def getPackageVersion() {
  def package = readJSON file: '${env.WORKSPACE}/app/package.json'
  echo package.version
  return package.version
}

Тогда вы сможете получить к нему доступ следующим образом.

def pcgVersion = getPackageVersion()
...