Skip to content

Instantly share code, notes, and snippets.

@grenade
Created December 17, 2013 16:38
Show Gist options
  • Save grenade/8007977 to your computer and use it in GitHub Desktop.
Save grenade/8007977 to your computer and use it in GitHub Desktop.
Get TeamCity to back itself up by creating a scheduled build configuration that runs this Powershell script.
param(
[string] $username,
[string] $password,
[string] $baseUrl = "http://teamcity:8111",
[int] $sleep = 10,
[int] $timeout = 600
)
function Execute-TeamCityBackup {
param(
[string] $baseUrl,
[string] $username,
[string] $password,
[string] $filenamePrefix = "TeamCity_Backup_",
[string] $addTimestamp = $true,
[string] $includeConfigs = $true,
[string] $includeDatabase = $true,
[string] $includeBuildLogs = $true, # change to false if the (very large) build log history is not required.
[string] $includePersonalChanges = $true
)
$url = [System.String]::Format("{0}/httpAuth/app/rest/server/backup?addTimestamp={1}&includeConfigs={2}&includeDatabase={3}&includeBuildLogs={4}&includePersonalChanges={5}&fileName={6}",
$baseUrl,
$addTimestamp,
$includeConfigs,
$includeDatabase,
$includeBuildLogs,
$includePersonalChanges,
$filenamePrefix)
$webRequest = [System.Net.WebRequest]::Create($url)
$webrequest.PreAuthenticate = $true
$webrequest.Credentials = New-Object System.Net.NetworkCredential($username, $password)
$webRequest.Method = "POST"
return ([Io.StreamReader]($webrequest.GetResponse().GetResponseStream())).ReadToEnd()
}
function Get-TeamCityBackupStatus {
param(
[string] $baseUrl,
[string] $username,
[string] $password
)
$url = "{0}/httpAuth/app/rest/server/backup" -f $baseUrl
$webrequest = [System.Net.WebRequest]::Create($url)
$webrequest.PreAuthenticate = $true
$webrequest.Credentials = New-Object System.Net.NetworkCredential($username, $password)
return ([Io.StreamReader]($webrequest.GetResponse().GetResponseStream())).ReadToEnd()
}
Write-Host ("Triggering backup.")
$backupFilename = Execute-TeamCityBackup -baseUrl $baseUrl -username $username -password $password
Write-Host ("Backup filename: {0}." -f $backupFilename)
Write-Host ("##teamcity[setParameter name='backupFilename' value='{0}']" -f $backupFilename)
$status = ""
$timeoutTimespan = New-Timespan -Seconds $timeout
$stopwatch = [diagnostics.stopwatch]::StartNew()
while (($status -ne "Idle") -and ($stopwatch.elapsed -lt $timeoutTimespan)) {
$status = Get-TeamCityBackupStatus -baseUrl $baseUrl -username $username -password $password
Write-Host ("Backup status: {0}" -f $status)
if ($status -ne "Idle"){
Start-Sleep -Seconds $sleep
}
}
if (($status -ne "Idle") -and ($stopwatch.elapsed -gt $timeout)) {
Write-Host ("Backup execution exceeded script timeout value of: {0} seconds." -f $timeout)
Write-Host ("Backup may still be in progress.")
}
elseif ($status -eq "Idle") {
Write-Host ("Backup complete.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment