I'm stuck on this issue for 2 days now but i don't seem to be able to delete Policy Assignments using Azure powershell commands or az commands.
All commands execute successfully and i am able to list all the assignments. The az delete command also executes successfully but does not delete the assignments, as they are still present in the Azure Portal policies.
Tried the following Powershell script:
$ResourceGroup = "PoliciesTest"
$query = "assignment"
# List policy assignments and extract the name and id
$assignments = az policy assignment list --resource-group $ResourceGroup --output json --only-show-errors | ConvertFrom-Json | Where-Object { $_.name -like "*$query*" }
# Iterate through the assignments and display name and id
foreach ($assignment in $assignments) {
Write-Host "Name: $($assignment.name)"
Write-Host "ID: $($assignment.id)"
Write-Host "--------------------"
az policy assignment delete --name $assignment.name --scope $assignment.id --debug
}
result of executing the script
There is one question on Stack overflow that has the same issue, but his issue was fixed by giving the scope. His solution does not work for me.
Not able to delete Azure Policy assignment using Azure commands in Powershell
If you get a 204
response when you try to delete an Azure Policy
assignment, it might take some time for the portal to remove it from the display. To verify, run the $assignments
variable.
I have below policy assignments with venkat
name in portal before running PowerShell code.
$scope = "/subscriptions/b83c1ed3-xxxxfjgjgj-b5ba-2bfhn4n5n6n"
$query = "venkat"
$assignments = az policy assignment list --scope $scope --output json --only-show-errors | ConvertFrom-Json | Where-Object { $_.displayName -like "*$query*" }
foreach ($assignment in $assignments) {
$name= $assignment.name
Write-Host "Name: $($name)"
$scopeid = $assignment.id
Write-Host "ID: $($scopeid)"
Write-Host "--------------------"
az policy assignment delete --name $name
}
Response:
After running the above code, the policy assignment was successfully deleted from the portal.
This script will remove the scope of the policy assignment: Resource group
.
$scope = "/subscriptions/b83xxxxx-xxxxx-44fb-xxxx-2b83aabcdgfc23f/resourceGroups/venkat"
$query = "allowed"
$assignments = az policy assignment list --scope $scope --output json --only-show-errors | ConvertFrom-Json | Where-Object { $_.displayName -like "*$query*" }
foreach ($assignment in $assignments) {
$name= $assignment.name
Write-Host "Name: $($name)"
$resourcegroup = $assignment.resourceGroup
Write-Host "Resource Group: $($resourcegroup)"
Write-Host "--------------------"
az policy assignment delete --name $name --resource-group $resourcegroup
}