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)
scriptWhat 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(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'
}
}
}
if($phrase -eq "stop-job")I hope this few lines of code can make your day easier.
{
$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__
}
}
}