Azure - Remove Resource Group Deployments

Octopus.AzurePowerShell exported 2019-04-25 by bmdixon belongs to ‘Azure’ category.

There is a cap in Azure that prevents having more than 800 deployments in the history at any given time: link to microsoft docs

This script helps alleviate this issue by limiting how many deployments are allowed exist, keeps the latest specified number of deployments, and will remove the rest.

What it does: Logs into Azure, selects the resource group of the app. Based on how many deployments it wants to keep, it will keep the latest X deployments and remove the rest. If there are less deployments than X to keep, the script will skip.

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Azure Subscription Account

AzureSubscriptionAccount =

null

Resource Group Name

Azure.RemoveResourceGroupDeployments.ResourceGroupName =

Enter the name of the resource group.

Number Of Deployments To Keep

Azure.RemoveResourceGroupDeployments.NumberOfDeploymentsToKeep =

Number Of Deployments To Keep. Defaults to empty and will not be used.

Number Of Days To Keep.

Azure.RemoveResourceGroupDeployments.NumberOfDaysToKeep =

Number Of Days To Keep. Defaults to empty and will not be used.

Script body

Steps based on this template will execute the following PowerShell script.

function Get-Param($Name, [switch]$Required, $Default) {
    $result = $null

    if ($null -ne $OctopusParameters) {
        $result = $OctopusParameters[$Name]
    }

    if ($null -eq $result) {
        $variable = Get-Variable $Name -EA SilentlyContinue
        if ($null -ne $variable) {
            $result = $variable.Value
        }
    }

    if ($null -eq $result) {
        if ($Required) {
            throw "Missing parameter value $Name"
        }
        else {
            $result = $Default
        }
    }

    return $result
}

Function Get-Deployments {
    Param(
        [Parameter(Mandatory = $true)]
        [string]$resourceGroupName
    )
    $listOfDeployments = Get-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName
    $azureDeploymentNameAndDate = @()
    $listOfDeployments | ForEach-Object { $azureDeploymentNameAndDate += [PSCustomObject]@{DeploymentName = $_.DeploymentName; Time = $_.Timestamp } }

    return $azureDeploymentNameAndDate
}

Function Remove-AzureRmResourceDeployments {

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [string]$resourceGroupName,

        [ValidateRange(0, 800)]
        [int]$numberOfDeploymentsToKeep,

        [int]$numberOfDaysToKeep
    )

    if ($null -ne $($numberOfDaysToKeep) -and $($numberOfDaysToKeep) -gt 0) {
        $azureDeploymentNameAndDate = Get-Deployments $resourceGroupName

        Write-Output "Found $($azureDeploymentNameAndDate.Count) deployments from the $resourceGroupName resource group"

        $itemsToRemove = $azureDeploymentNameAndDate | Where-Object { $_.Time -lt ((get-date).AddDays( - $($numberOfDaysToKeep))) }
        $numberOfItemsToRemove = $itemsToRemove | Measure-Object

        if ($numberOfitemsToRemove.Count -eq 0) {
            Write-Output "There are no deployments older than $($numberOfDaysToKeep) days old in $($resourceGroupName)... skipping"
        }
        else {
            Write-Output "Deleting $($numberOfitemsToRemove.Count) deployment(s) from $($resourceGroupName) as they are more than $($numberOfDaysToKeep) days old."
            $itemsToRemove | ForEach-Object { Write-Output "Deleting $($_.DeploymentName)"; Remove-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -name $_.DeploymentName }
        }
    }

    if ($null -ne $($numberOfDeploymentsToKeep) -and $($numberOfDeploymentsToKeep) -gt 0) {
        $azureDeploymentNameAndDate = Get-Deployments $resourceGroupName

        Write-Output "Found $($azureDeploymentNameAndDate.Count) deployments from the $resourceGroupName resource group"

        $itemsToRemove = $azureDeploymentNameAndDate | Sort-Object Time -Descending | select-object -skip $numberOfDeploymentsToKeep
        $numberOfItemsToRemove = $itemsToRemove | Measure-Object

        if ($numberOfitemsToRemove.Count -eq 0) {
            Write-Output "Max number of deployments set to keep is $numberOfDeploymentsToKeep... skipping"
        }
        else {
            Write-Output "Maximum number of deployments exceeded. Deleting $($numberOfitemsToRemove.Count) deployment(s) from $($resourceGroupName)"
            $itemsToRemove | ForEach-Object { Write-Output "Deleting $($_.DeploymentName)"; Remove-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -name $_.DeploymentName }
        }
    }
}

## --------------------------------------------------------------------------------------
## Input
## --------------------------------------------------------------------------------------

$resourceGroupName = Get-Param 'Azure.RemoveResourceGroupDeployments.ResourceGroupName' -Required
$numberOfDeploymentsToKeep = Get-Param 'Azure.RemoveResourceGroupDeployments.NumberOfDeploymentsToKeep' -Default 0
$numberOfDaysToKeep = Get-Param 'Azure.RemoveResourceGroupDeployments.NumberOfDaysToKeep' -Default 0

Remove-AzureRmResourceDeployments -resourceGroupName $resourceGroupName -numberOfDeploymentsToKeep $numberOfDeploymentsToKeep -numberOfDaysToKeep $numberOfDaysToKeep -Verbose

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "7351a3e7-df59-4e0c-863a-dca6f33ad2e1",
  "Name": "Azure - Remove Resource Group Deployments",
  "Description": "There is a cap in Azure that prevents having more than 800 deployments in the history at any given time: link to microsoft docs\n\nThis script helps alleviate this issue by limiting how many deployments are allowed exist, keeps the latest specified number of deployments, and will remove the rest.\n\nWhat it does: Logs into Azure, selects the resource group of the app. Based on how many deployments it wants to keep, it will keep the latest X deployments and remove the rest. If there are less deployments than X to keep, the script will skip.",
  "Version": 2,
  "ExportedAt": "2019-04-25T13:33:59.856Z",
  "ActionType": "Octopus.AzurePowerShell",
  "Author": "bmdixon",
  "Packages": [],
  "Parameters": [
    {
      "Id": "30a798bd-db11-44d3-82bd-28c3b13e77a5",
      "Name": "AzureSubscriptionAccount",
      "Label": "Azure Subscription Account",
      "HelpText": null,
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "AzureAccount"
      }
    },
    {
      "Id": "27c68d1f-7fdc-4e10-aa4a-77a0ff55eb29",
      "Name": "Azure.RemoveResourceGroupDeployments.ResourceGroupName",
      "Label": "Resource Group Name",
      "HelpText": "Enter the name of the resource group.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    },
    {
      "Id": "2adcf1a9-d319-4ed3-80e7-4c533ddbe5cd",
      "Name": "Azure.RemoveResourceGroupDeployments.NumberOfDeploymentsToKeep",
      "Label": "Number Of Deployments To Keep",
      "HelpText": "Number Of Deployments To Keep. Defaults to empty and will not be used.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "c5ce930b-ea04-42b8-8ade-d167a26dab2a",
      "Name": "Azure.RemoveResourceGroupDeployments.NumberOfDaysToKeep",
      "Label": "Number Of Days To Keep.",
      "HelpText": "Number Of Days To Keep. Defaults to empty and will not be used.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.Azure.AccountId": "#{AzureSubscriptionAccount}",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptBody": "function Get-Param($Name, [switch]$Required, $Default) {\n    $result = $null\n\n    if ($null -ne $OctopusParameters) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($null -eq $result) {\n        $variable = Get-Variable $Name -EA SilentlyContinue\n        if ($null -ne $variable) {\n            $result = $variable.Value\n        }\n    }\n\n    if ($null -eq $result) {\n        if ($Required) {\n            throw \"Missing parameter value $Name\"\n        }\n        else {\n            $result = $Default\n        }\n    }\n\n    return $result\n}\n\nFunction Get-Deployments {\n    Param(\n        [Parameter(Mandatory = $true)]\n        [string]$resourceGroupName\n    )\n    $listOfDeployments = Get-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName\n    $azureDeploymentNameAndDate = @()\n    $listOfDeployments | ForEach-Object { $azureDeploymentNameAndDate += [PSCustomObject]@{DeploymentName = $_.DeploymentName; Time = $_.Timestamp } }\n\n    return $azureDeploymentNameAndDate\n}\n\nFunction Remove-AzureRmResourceDeployments {\n\n    [CmdletBinding()]\n    Param(\n        [Parameter(Mandatory = $true)]\n        [string]$resourceGroupName,\n\n        [ValidateRange(0, 800)]\n        [int]$numberOfDeploymentsToKeep,\n\n        [int]$numberOfDaysToKeep\n    )\n\n    if ($null -ne $($numberOfDaysToKeep) -and $($numberOfDaysToKeep) -gt 0) {\n        $azureDeploymentNameAndDate = Get-Deployments $resourceGroupName\n\n        Write-Output \"Found $($azureDeploymentNameAndDate.Count) deployments from the $resourceGroupName resource group\"\n\n        $itemsToRemove = $azureDeploymentNameAndDate | Where-Object { $_.Time -lt ((get-date).AddDays( - $($numberOfDaysToKeep))) }\n        $numberOfItemsToRemove = $itemsToRemove | Measure-Object\n\n        if ($numberOfitemsToRemove.Count -eq 0) {\n            Write-Output \"There are no deployments older than $($numberOfDaysToKeep) days old in $($resourceGroupName)... skipping\"\n        }\n        else {\n            Write-Output \"Deleting $($numberOfitemsToRemove.Count) deployment(s) from $($resourceGroupName) as they are more than $($numberOfDaysToKeep) days old.\"\n            $itemsToRemove | ForEach-Object { Write-Output \"Deleting $($_.DeploymentName)\"; Remove-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -name $_.DeploymentName }\n        }\n    }\n\n    if ($null -ne $($numberOfDeploymentsToKeep) -and $($numberOfDeploymentsToKeep) -gt 0) {\n        $azureDeploymentNameAndDate = Get-Deployments $resourceGroupName\n\n        Write-Output \"Found $($azureDeploymentNameAndDate.Count) deployments from the $resourceGroupName resource group\"\n\n        $itemsToRemove = $azureDeploymentNameAndDate | Sort-Object Time -Descending | select-object -skip $numberOfDeploymentsToKeep\n        $numberOfItemsToRemove = $itemsToRemove | Measure-Object\n\n        if ($numberOfitemsToRemove.Count -eq 0) {\n            Write-Output \"Max number of deployments set to keep is $numberOfDeploymentsToKeep... skipping\"\n        }\n        else {\n            Write-Output \"Maximum number of deployments exceeded. Deleting $($numberOfitemsToRemove.Count) deployment(s) from $($resourceGroupName)\"\n            $itemsToRemove | ForEach-Object { Write-Output \"Deleting $($_.DeploymentName)\"; Remove-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -name $_.DeploymentName }\n        }\n    }\n}\n\n## --------------------------------------------------------------------------------------\n## Input\n## --------------------------------------------------------------------------------------\n\n$resourceGroupName = Get-Param 'Azure.RemoveResourceGroupDeployments.ResourceGroupName' -Required\n$numberOfDeploymentsToKeep = Get-Param 'Azure.RemoveResourceGroupDeployments.NumberOfDeploymentsToKeep' -Default 0\n$numberOfDaysToKeep = Get-Param 'Azure.RemoveResourceGroupDeployments.NumberOfDaysToKeep' -Default 0\n\nRemove-AzureRmResourceDeployments -resourceGroupName $resourceGroupName -numberOfDeploymentsToKeep $numberOfDeploymentsToKeep -numberOfDaysToKeep $numberOfDaysToKeep -Verbose\n"
  },
  "Category": "Azure",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/azure-remove-resource-group-deployments.json",
  "Website": "/step-templates/7351a3e7-df59-4e0c-863a-dca6f33ad2e1",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRF////AHjXf7vrv931QJrh7/f8EIDaIIncMJHfYKvmz+b3n8zw3+76j8Ttr9XycLPpUKLkkKvYFAAABGZJREFUeNrsnNmCqjoQRc1MEiD8/9cer7Yt2KBJZQC8ez07sKlKTQlcLgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzoUSnt8YxXlFuGHSbIaxvj+fip4btkLn1blkWLaF5v03yLhLOYlVuGYfMOMZzNGxCOzhjTJqFkXnjq3Dr1yyvPI3hGl3Ih3zzHHNKudRstRhX5O58vIcShY67Gq6EPIESlzUWvazaGAOGbvU7ArDu/g8M4o8opDZWvbvPzlL/MMBE8jT9T9W7PbAJlHPTBFRf9yVTEcs63msXz2UHLSgf650G/d5t+wjbxxB2UCMqGrk8/LFSD7uJMeNt5bcJCyQZyAe5Fo9KYfWS2flQrr4b4tpuzaeWjYs49rt9LHf9uZD7+VbyVi9EBNrjYjuq2sxQOrl+p+HuBVu45qvqfq691ttYFQ5KyKbyJgaIY/NGxrlWZwlwGvmvu1oY3PuAv0niTq6tZ78jk//9uc1r1r4lQ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Thursday, April 25, 2019