Last active
February 15, 2018 17:07
-
-
Save gknapp/7b4dae4502b0d3d3c324ba19483b419e to your computer and use it in GitHub Desktop.
Post commit hook to run a Jenkins build
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Powershell post-commit hook. Can be used with Tortoise SVN as a | |
# client side hook using: | |
# powershell.exe C:\path\to\postcommit.ps1 <JenkinsJob> <AuthToken> <JenkinsUser> <APIToken> | |
# | |
# You may need to bypass the Execution Policy (default is Restricted): | |
# | |
# powershell.exe -ExecutionPolicy Bypass C:\path\to\postcommit.ps1 ... | |
# | |
# JenkinsJob is the job name | |
# AuthToken is set in job Build Triggers | |
param( | |
[string] $job, | |
[string] $jobToken, | |
[string] $username, | |
[string] $apiToken, | |
[string] $cause = "post commit ($($env:UserName))", | |
[string] $jenkinsHost = 'jenkins:8080' | |
) | |
# --- start helper functions --- | |
function Basic-Auth { | |
param([string] $username, [string] $apiToken) | |
'Basic ' + [Convert]::ToBase64String( | |
[Text.Encoding]::ASCII.GetBytes("$($username):$($apiToken)") | |
) | |
} | |
function Build-AuthHeader { | |
param([string] $username, [string] $apiToken) | |
@{Authorization = Basic-Auth $username $apiToken} | |
} | |
function Get-BuildUrl { | |
"{0}/job/{1}/build?token={2}&cause={3}" -f $args; | |
} | |
function Get-CsrfHeader { | |
param([string] $baseUri, [hashtable] $headers) | |
$params = @{ | |
uri = "$($baseUri)/crumbIssuer/api/xml" | |
method = 'GET' | |
Headers = $headers | |
} | |
[xml] $crumb = Invoke-RestMethod @params -ErrorAction Stop | |
@{ | |
name = $crumb.defaultCrumbIssuer.crumbRequestField | |
value = $crumb.defaultCrumbIssuer.crumb | |
} | |
} | |
function Trigger-Build { | |
param([string] $url, [hashtable] $headers) | |
$params = @{ | |
uri = $url | |
method = 'POST' | |
Headers = $headers | |
} | |
Invoke-RestMethod @params -ErrorAction Stop | |
} | |
# --- end helper functions --- | |
Try { | |
$baseUri = "http://$($jenkinsHost)" | |
$headers = Build-AuthHeader $username $apiToken | |
$csrf = Get-CsrfHeader $baseUri $headers | |
$headers.add($csrf.name, $csrf.value) | |
$url = Get-BuildUrl $baseUri $job $jobToken $cause | |
Trigger-Build $url $headers | |
} Catch { | |
Write-Host $PSItem.ToString().Trim() -ForegroundColor Yellow | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment