Skip to content

Instantly share code, notes, and snippets.

@ChaseFlorell
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChaseFlorell/f1e79262d66f5bd68149 to your computer and use it in GitHub Desktop.
Save ChaseFlorell/f1e79262d66f5bd68149 to your computer and use it in GitHub Desktop.
$ErrorActionPreference = "Stop"
if(!$OctopusParameters){
Write-Warning 'The orchestrator package must only be deployed from within Octopus Deploy.'
exit 0
}
# get's the current location
$here = Split-Path $script:MyInvocation.MyCommand.Path
# makes sure the octo.exe is in the path
$env:Path += ";$here\tools"
# Octopus Parameters
$deployer = $OctopusParameters['GCTS.Deployment.CreatedBy.EmailAddress'] # Defined by TeamCity / Octopus (if teamcity doesn't set it, it'll be the CreatedBy.Email from Octopus - definded in GCTS Shared VariableSet)
$environment = $OctopusParameters['Octopus.Environment.Name'] # Defined by Octopus
$environmentId = $OctopusParameters['Octopus.Environment.Id'] # Defined by Octopus
$notes = $OctopusParameters['Octopus.Release.Notes'] # Defined by Octopus
$specificMachines = $OctopusParameters['Octopus.Deployment.SpecificMachines'] # Defined by Octopus
$version = $OctopusParameters['Octopus.Release.Number'] # Defined by Octopus
$apiKey = $OctopusParameters['GCTS.Orchestrator.APIKey'] # Defined in Orchestrator project
$loadData = $OctopusParameters['GCTS.Orchestrator.loadData'] # Defined in Orchestrator project
$rebuildDb = $OctopusParameters['GCTS.Orchestrator.rebuildDb'] # Defined in Orchestrator project
$url = $OctopusParameters['Octopus.Web.BaseUrl'] # Depricated in Octopus - Now defined in TransCanada Variable Set
# Create a new Release Notes file because - eff.
$notes | Out-File "$here\releaseNotes.md"
# Packages/Projects to Deploy
$apps = @(
'GCTS App',
'GCTS CommonDataService',
'GCTS ContractsService',
'GCTS FlowingGas',
'GCTS Invoicing',
'GCTS JobSchedulingService')
# A little Tom Hackery to get the machine names directly from the Octopus API.
$headers = @{"X-Octopus-ApiKey" = $apiKey}
$machinesInEnvironmentUri = "$url/api/environments/$environmentId/machines/"
$specificMachineNames = @()
$machines = Invoke-RestMethod -Method Get -Uri $machinesInEnvironmentUri -Headers $headers
$specificMachines.Split(",", [System.StringSplitOptions]::RemoveEmptyEntries) | % {
$machineId = $_
$machines.Items | % {
if($_.Id -eq $machineId) {
$specificMachineNames += $_.Name
}
}
}
# Loop over the apps, and deploy them.
$apps | % {
Write-Host "Creating a $version release for $_ if it does not already exist."
Octo create-release --server=$url --apiKey=$apiKey --project=$_ --packageversion=$version --version=$version --releaseNotesFile="$here\releaseNotes.md" --ignoreexisting
Write-Host ""
Write-Host "Deploying $_ to the following machines in the $environment environment."
Write-Host "$specificMachineNames"
# if you're NOT using --progress, and --waitForDeployment, please make sure you set `OctopusBypassDeploymentMutex` to `True` on the orchestrator (this) project.
# --waitForDeployment --progress
Octo deploy-release --server=$url --apiKey=$apiKey --project=$_ --deployTo=$environment --version=$version --specificMachines=$specificMachineNames --variable="prompt.loadData:$loadData" --variable="prompt.rebuildDatabase:$rebuildDb" --variable="GCTS.Deployment.CreatedBy.EmailAddress:$deployer"
}
# note: make the octopusServer and the octopusApiKey configuration parameters (and set the key as a hidden password)
# credit for getting me going in the right direction
# http://blogs.lessthandot.com/index.php/uncategorized/access-git-commits-during-a-teamcity-build-using-powershell/
$project = "%Octopus.Project%"
$deployTo = "%Octopus.DefaultEnvironment%"
$vcsGitUrl = "http://papp03016:8080/tfs/SharedCollection/_git/Gas%20Customer%20Transactional%20System" #normally this should be a config param, but we have spaces in the string, and that sucks balls when it comes to TeamCity parameters
$username = "%system.teamcity.auth.userId%"
$password = "%system.teamcity.auth.password%"
$serverUrl = "%teamcity.serverUrl%"
$buildTypeId = "%system.teamcity.buildType.id%"
$buildId = "%teamcity.build.id%"
$gitPath = "%env.TEAMCITY_GIT_PATH%"
$buildNumber = "%build.vcs.number%"
$buildVersion = "%BuildVersion%"
$octopusApiKey = "%Octopus.BuildDeployBot.APIKey%"
$octopusServer = "%Octopus.Server.Url%"
$checkoutDir = "%system.teamcity.build.checkoutDir%"
$fs = New-Object -ComObject Scripting.FileSystemObject
function Get-TeamCityLastSuccessfulRun{
$AuthString = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$username`:$password"))
$Url = "$serverUrl/app/rest/buildTypes/id:$buildTypeId/builds/status:SUCCESS"
$Content = Invoke-WebRequest "$Url" -Headers @{"Authorization" = "Basic $AuthString"} -UseBasicParsing
return $Content
}
function Get-CommitsFromGitLog([string] $StartCommit, [string] $EndCommit){
$git = $fs.GetFile("$gitPath").shortPath
$overviewUrl = "$serverUrl/viewLog.html?buildId=$buildId&buildTypeId=$buildTypeId&tab=buildResultsDiv"
$commitUrl = "$($vcsGitUrl.TrimEnd('.git'))/commit"
$Cmd = "$git log --pretty=format:""%s [%h...]($commitUrl/%H)"" $StartCommit...$EndCommit"
$Result = $(Invoke-Expression "$path $Cmd")
$nl = [environment]::NewLine
[string]$str = "##TeamCity Alpha Deployment $nl" + "[click here for build overview]($overviewUrl) $nl$nl"
$Result | where {-not $_.StartsWith("Merge branch")} | % {$str += " - $_ $nl"}
$str += "$nl-----"
return $str
}
function Get-LastCommitterEmail {
$git = $fs.GetFile("$gitPath").shortPath
$cmd = "$git log -1 --pretty=""%ae"""
$Result = $(Invoke-Expression "$path $Cmd")
return $Result
}
$Run = Get-TeamCityLastSuccessfulRun
$LatestCommitFromRun = (Select-Xml -Content "$Run" -Xpath "/build/revisions/revision/@version").Node.Value
$CommitsSinceLastSuccess = Get-CommitsFromGitLog -StartCommit "$LatestCommitFromRun" -EndCommit "$buildNumber"
$deployer = Get-LastCommitterEmail
$CommitsSinceLastSuccess > "$checkoutDir\build-artifacts\ReleaseNotes.md"
$Cmd = "octo.exe create-release --apiKey=$octopusApiKey --server='$octopusServer' --project='$project' --deployto='$deployTo' --enableServiceMessages --packageversion='$buildVersion' --releaseNotesFile='$checkoutDir\build-artifacts\ReleaseNotes.md' --variable='GCTS.Deployment.CreatedBy.EmailAddress:$deployer' --ignoreexisting"
Invoke-Expression $cmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment