2018-10-24

Jenkins stops pipeline from Powershell

When you realize inside some job that you want to terminate running job in Jenkins you need to find way, hot to pass message to proper level where is Jenkins actually able to terminate the job. I am using this way with calling authorized URL which is terminating the job.

Jenkinsfile pipline is calling powershell and passing there API token from credentials (manually inserted to Jenkins => Credentials)
script
{
    if(env.GIT_PREVIOUS_SUCCESSFUL_COMMIT !=  null)
    {
        withCredentials([string(credentialsId: 'JenkinsAPIcredentials', variable: 'apistring')])
        {
            echo 'checking number of changes and stopping job if nothing new happened'
            powershell 'powershell -File $env:WORKSPACE\\stop-script.ps1 -phrase "stop-job" -buildNumber $env:BUILD_NUMBER -gitprevious $env:GIT_PREVIOUS_SUCCESSFUL_COMMIT -gitcurrent $env:GIT_COMMIT -jenkinsUrl $env:JENKINS_URL -buildIDurl $env:BUILD_URL -apistring $env:apistring'
        }
    }
}
What is happening inside powershell script? There is needed to generate authorized POST call to Jenkins server, luckily is process few lines of code. Part of code is missing definition of parameters in Powershell.
if($phrase -eq "stop-job")
{       
    $commitsnumprevious = (git rev-list --count $gitprevious)
    $commitsnumactual = (git rev-list --count $gitcurrent)
    $difference =  $commitsnumactual-$commitsnumprevious

    if($difference -le 0)
    {
        $url = $buildIDurl+'stop'
        $Bytes = [System.Text.Encoding]::UTF8.GetBytes($apistring)
        $Base64bytes = [System.Convert]::ToBase64String($Bytes)
        $Headers = @{ "Authorization" = "Basic $Base64bytes"}
        $CrumbIssuer = "$jenkinsUrl/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,`":`",//crumb)"
        $Crumb = Invoke-WebRequest -UseBasicParsing $CrumbIssuer -Headers $Headers
        $Regex = '^Jenkins-Crumb:([A-Z0-9]*)'
        $Matches = @([regex]::matches($Crumb, $Regex, 'IgnoreCase'))
        $RegCrumb = $Matches.Groups[1].Value
        $Headers.Add("Jenkins-Crumb", "$RegCrumb")

        try
        {
            $response = Invoke-WebRequest -Uri $url -Headers $Headers -Method POST
        }
        catch
        {           
            Write-Error "Stopping of job failed! " $_.Exception.Response.StatusCode.Value__
        }       
    }
}
I hope this few lines of code can make your day easier.
 

2018-10-16

Jenkins checkout git by commit id parameter

Discussion forums on Internet are providing answers for your question "how to check out specific git hash in Jenkins" quite easily for a manual procedure, but if you want to do it programmatically inside pipeline defined in Jenkins file or even by parameter problems raise.


It makes sense to check out specific git hash because it's unique inside repository and if you add git sha in job configuration GUI (Branch Specifier (blank for 'any')) then you really get the specific version in your workspace, so where is the problem?


Inside pipeline, block checkout you need to echo this commit from the variable by only one syntax even there are at least 3 other different ways usually works for printing the variable.

checkout([$class: 'GitSCM', branches: [[name: "ECHO GIT SHA HERE"]], userRemoteConfigs: [[credentialsId: 'string', url: 'string']]])

So the only one correct way is to use:
  • branches: [[name: "${params.BRANCH_NAME}"]],

because this are not working (but they are still printing value):
  • branches: [[name: env.BRANCH_NAME]], 
  • branches: [[name: ${env.BRANCH_NAME}]], 
  • branches: [[name: "${BRANCH_NAME}"]],


So to solve this I burned many hours. The syntax of Groovy is not enough mature yet, anyway I hope this can help you and if you need to do more magic with parameters as git values, I can recommend this plugin.