I would probably do this in two steps:
Create a runbook which uses the Search-AzGraph
cmdlet from the Az.ResourceGraph
module. Here is an example query that retrieves all NSG rules using Resource Graph: https://blog.blksthl.com/2020/10/02/list-all-nsg-security-rules-in-one-query-using-azure-resource-graph/
Create a 2nd runbook for remediation, that uses Set-AzNetworkSecurityGroup
and takes parameters to remediate any detected misconfigured resources.
The benefit of doing it this way is that it's much quicker using the resourceGraph to query all resources than using the native AzVm
or Get-AzNetworkSecurityGroup
and looping through each resource.
Splitting out the get/set logic into separate runbooks gives you greater visibility, activity logs per runbook and also if you need to change the output from just remediation, you can asynchronously call runbooks so you could e.g. call an action group for an alert then remediate and the logic would be isolated to a specific runbook.