Search code examples
azureazure-policy

Programmatically triggering azure policy remediation


I have got azure policy auto remediation in place, however the process is a manual one where the remediation tasks needs to be manually triggered. I was wondering if there is a way to programmatically trigger the running of the remediation job.

I can see the remediation tasks, however they are a manual step that has to be triggered when required. I would ideally love to automate the process.

Any thoughts on a potential solution here.


Solution

  • Programmatically triggering azure policy remediation

    Here is the Azure PowerShell code to trigger the remediation without manual intervention., You want to automate this process, you can use Azure automation account, follow the stack link to create automation account.

    $policyassignmentNames = @("Storage enable Policy", "Network Security Group rule deny", "NSG_Rule_Deny", "JIT Port deny", "Azure Policy to modify Log analytics workspace destination of a data collection rule","JIM_Port_3389 and 22 Restricted")
    
    $policyAssignments = Get-AzPolicyAssignment -BackwardCompatible -WarningAction silentlyContinue | Where-Object { $policyassignmentNames -contains $_.DisplayName }
    
    foreach ($policy in $policyAssignments){
    
    $remediatename= "Remeadite." + $policy.DisplayName
    
    write-output "Starting the remediation with Policy Assignment Name :$($policy.DisplayName)"
    
    Start-AzPolicyRemediation -Name "$remediatename" -PolicyAssignmentId $policy.PolicyAssignmentId -ResourceDiscoveryMode ReEvaluateCompliance
    }
    

    Output:

    enter image description here