Remove Azure Initiative with related policies

Hello Scripters! Remove Azure Initiative is the topic on which I was fighting last time and today I have for you PowerShell script which will remove it with correlated policies and assignments.

Azure policies allows cloud admin/devops to manage Azure governance model. You can block specific resources to be created, enforce enabling diagnostic logs on all resources or simply inherit tags from resource group to resources inside. But what is initiative? It’a a collection of Azure policies which integrates them in order to achieve some goal.

During my work I tested few scenarios and script to remove Azure initiative was really needed as doing this manually was really annoying.

Prerequisites:

  • Az module installed
  • Proper permission on subscription level (best Owner)
  • Initiatives already created

Script:

param(
    [Parameter(Mandatory = $true)][string]$InitiativeName,
    [Parameter(Mandatory = $true)][bool]$RemoveAssignment
)

$initiative = Get-AzPolicySetDefinition -Name $InitiativeName -ErrorAction Ignore
if ($null -ne $initiative) {
    
    $assignment = Get-AzPolicyAssignment -PolicyDefinitionId $initiative.ResourceId -ErrorAction Ignore
    if ($null -ne $assignment) {
        if ($RemoveAssignment) {
            
            Write-Output "Assignment for initiative $InitiativeName will be removed as RemoveAssignment parameter was set to true."
            Remove-AzPolicyAssignment -Id $assignment.PolicyAssignmentId | Out-Null
            Write-Output "Assignment $($assignment.Name) has been removed."            

            $Policies = (Get-AzPolicySetDefinition -Name $InitiativeName).Properties.policyDefinitions.policyDefinitionId
            Remove-AzPolicySetDefinition -Name $InitiativeName -Force | Out-Null
            Write-Output "Initiative $InitiativeName has been removed." 

            foreach ($policy in $Policies) {
                Write-Output "Removing policy $policy assgined to $InitiativeName"
                Remove-AzPolicyDefinition -Id $policy -Force | Out-Null
                Write-Output "Policy $policy has been removed."
            }  
                  
        }
        else {
            Write-Output "Remove assignment attribute was set to false."
        }
    }
}
else {
    Write-Output "Initiative $InitiativeName not found."
}

I hope it will be usefull for some of you 😉

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.