Last active
December 7, 2022 16:07
-
-
Save s4parke/80903b850f4e36172a74b59ecfafbcb9 to your computer and use it in GitHub Desktop.
Azure CLI script to trigger Policy scans at management group level including all subscriptions in all subgroups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/env/bin/bash | |
# Azure CLI script to trigger Policy scans at management group level including all subscriptions in all subgroups. | |
# Usage | |
# ./az-policy-scan-mgroup.sh [mgroup] | |
# Parameters | |
# [mgroup] - Optional child management group. Defaults to mydefaultmgroup. | |
# Dependencies: | |
# az extension add --name resource-graph | |
# Examples | |
# ./az-policy-scan-mgroup.sh // All | |
# ./az-policy-scan-mgroup.sh mgroupowow // Only one management group called 'mgroupwow' | |
# If no management group is entered, use mydefaultmgroup as the default | |
TARGET_MG=${1:-mydefaultmgroup} | |
ROOT_MG="mydefaultmgroup" | |
success=0 | |
fail=0 | |
target_management_group="$TARGET_MG" | |
root_management_group_id="$ROOT_MG" | |
# Graph query for subs | |
query="resourcecontainers | where type == 'microsoft.resources/subscriptions' | mv-expand mgAncestor = properties.managementGroupAncestorsChain | extend state = properties.state | where mgAncestor.name =~ '${target_management_group}' | where state == 'Enabled' | summarize count() by subscriptionId" | |
subscription_ids=$(az graph query -q "${query}" --management-groups "${root_management_group_id}" --query 'data[].subscriptionId' -o tsv) | |
for subscription_id in ${subscription_ids}; do | |
printf "[$count] Set context ${subscription_id}..." | |
az account set -s ${subscription_id} | |
if [ $? -eq 0 ]; then | |
printf "OK... Trigger Scan..." | |
az policy state trigger-scan --subscription "${subscription_id}" --no-wait | |
printf "DONE\n" | |
((count=count+1)) | |
else | |
printf "FAILED\n" | |
((count=count-1)) | |
((fail=fail+1)) | |
fi | |
done | |
echo "[$count] Scanned subscriptions in group ($target_management_group)" | |
echo "[$fail] Failed subscriptions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment