I want to set a global default retention policy of 3 runs per environment. Is there a way to set that in Octopus?
There’s not a way to configure a global default in the UI, but you can use the API with a Runbook executing on a schedule to make sure that your preferred default is set.
This script is provided as an example. Please verify and test before using in your instance.
This script will look for Runbooks with the default policy of 100 runs per environment and update them to store only 3 runs per environment. It acts only on the current Space, but you can also use the API to iterate over other Spaces and update their Runbooks as well.
You will need a variable defiend for the API key in your runbook project.
$OctopusURL = $OctopusParameters["Octopus.Web.ServerUri"]
$OctopusAPIkey = $OctopusParameters["Global.Octopus.APIKey"]
$header = @{ "X-Octopus-ApiKey" = $octopusAPIKey }
function UpdateRunbooksInSpace {
param(
[Parameter(Position = 0, Mandatory)]$Space,
$RunsToKeep = 3
)
Write-Output "Getting runbooks for space '$($space.Name)'"
$runbooks = Invoke-RestMethod $OctopusURL/api/$($space.Id)/runbooks/all -Headers $header
foreach ($runbook in $runbooks) {
$project = Invoke-RestMethod $OctopusURL/api/$($space.Id)/projects/$($runbook.ProjectId) -Headers $header
Write-Host "Checking retention policy for runbook '$($runbook.Name)' in project '$($project.Name)'"
$retentionPolicy = $runbook.RunRetentionPolicy
if ($retentionPolicy.QuantityToKeep -eq 100 -and -not $retentionPolicy.ShouldKeepForever) {
Write-Host "Retention policy is set to the default. Updating to keep $runsToKeep runs."
$runbook.RunRetentionPolicy.QuantityToKeep = $runsToKeep
$body = $runbook | ConvertTo-Json -Depth 5
Invoke-RestMethod $OctopusURL/api/$($space.Id)/runbooks/$($runbook.Id) -Headers $header -Method Put -Body $body | Out-Null
}
}
}
$spaceId = $OctopusParameters["Octopus.Space.Id"]
$space = Invoke-RestMethod $OctopusURL/api/spaces/$spaceId -Headers $header
UpdateRunbooksInSpace $space
<#
$spaces = Invoke-RestMethod $OctopusURL/api/spaces/all -Headers $header
foreach ($space in $spaces) {
UpdateRunbooksInSpace $space
}
#>
1 Like