Gousiya Sayyad
Gousiya Sayyad

Reputation: 1

Delete All Azure Policies at once

Is there any way to delete all the assigned policies at once in azure? I have deployed 93 policies through azure blueprints and when I have unassigned the blueprint, the blueprint assignment is deleted but policies remains in the "Policy" assignments. Thank you in advance

Upvotes: 0

Views: 1865

Answers (2)

OliP
OliP

Reputation: 9

I wanted to share my script with you! I've just developed a script that efficiently removes all PolicyAssignments associated with a specific subscription.

You can also use the filter: $PolicyAssignmentNameNotLike

Use Login-AzAccount

$azSubcriptions = Get-AzSubscription -tenantid '## Your TenantID ##'

$PolicyAssignmentNameNotLike = "ASC Default*"

Foreach($azSubcription in $azSubcriptions){

    Write-verbose "RUN : Subscription : $($azSubcription.name)" -Verbose

    $azPolicyAssignments = ((Invoke-AzRestMethod -uri "https://management.azure.com/subscriptions/$($azSubcription.id)/providers/Microsoft.Authorization/policyAssignments?api-version=2022-06-01").content | convertfrom-json).value

    Foreach($azPolicyAssignment in $azPolicyAssignments.where{$_.properties.displayName -notlike $PolicyAssignmentNameNotLike}){

        Write-verbose "DELETE PolicyAssignment : $($azPolicyAssignment.properties.displayName)" -verbose

        $webrequest = Invoke-AzRestMethod -method DELETE -uri "https://management.azure.com/subscriptions/$($azSubcription.id)/providers/Microsoft.Authorization/policyAssignments/$($azPolicyAssignment.name)?api-version=2022-06-01"

        if($webrequest.StatusCode -eq 200){
            Write-verbose "Suceeded to Delete Policy Assignment: $($azPolicyAssignment.name)"
        } else {
            Write-Error "Failed to Delete Policy Assignment: $($azPolicyAssignment.name)"
        }
    }

}

Upvotes: 0

Asad
Asad

Reputation: 108

You will need to write a script for that. If you are using PowerShell then you can use Remove-AzPolicyDefinition to delete a policy. So firstly, get a list of all the policies using Get-AzPolicyDefinition, then loop through that list and delete each policy using Remove-AzPolicyDefinition. You can also implement this solution using Azure CLI instead of PowerShell. Choose whatever you are more comfortable with.

Note: Use Remove-AzPolicyAssignment if you only want to remove the policy assignment instead of the definition.

Upvotes: 0

Related Questions