-
Notifications
You must be signed in to change notification settings - Fork 1
/
cleanup_sub_rg.sh
executable file
·81 lines (68 loc) · 2.24 KB
/
cleanup_sub_rg.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source ${DIR}/functions.sh
print-usage() {
echo "
This script deletes inactive resource groups on the given subscription.
Inactive resource groups are the ones with no non-audit activity in last 7 days.
The script takes 2 arguments: Id of the subscription to work on and/or whether it's a 'realrun'.
In dryrun mode, resource groups will be examed but not deleted. Any string other than 'realrun' will result in dryrun.
e.g.
$0 my-test-subscrioption --> dry run
$0 my-test-subscrioption realrun --> real run
$0 my-test-subscrioption realrun | tee ./log --> real run with logs recorded
"
}
# Errors
INVALID_ARGS=8001
if (( $# == 0 )); then
print-usage
exit ${INVALID_ARGS}
fi
subId=$1
realRun=0
if (( $# == 2 )) && [ $2 == 'realrun' ]; then
realRun=1
fi
echo "Clean up subscription '$subId' 'realrun'=${realRun}"
cmd="az group list --subscription '${subId}' --query \"[].{name:name, location:location, managedBy:managedBy, state:properties.provisioningState, preserve:tags.preserve}\" -o tsv"
echo "$cmd"
rgs=`eval ${cmd}`
rgCnt=$(echo "$rgs" | wc -l)
echo "FOUND "${rgCnt}" RESOURCE GROUPS IN SUBSCRIPTION '${subId}'"
for line in ${rgs}
do
#echo ${line}
#readarray -t -d $'\t' f <<< $line
IFS=$'\t' read -r -a f <<< $line
echo
echo "+++++++++++++PROCESS RG: ${f[0]} +++++++++++++"
# skip managed rg and rg in Deleting state
if [ ${f[2]} != 'None' ]; then
echo "SKIP MANAGED RG: ${f[0]} IS MANAGED BY ${f[2]}"
continue
elif [ ${f[3]} == 'Deleting' ]; then
echo "SKIP RG UNDER DELETION: ${f[0]}"
continue
fi
activities="$(get-non-audit-activities $subId ${f[0]} 7d)"
if [ -z "${activities}" ]; then
echo "NO NON-AUDIT ACTIVITIES IN LAST 7 DAYS. SHOULD DELETE: ${f[0]}"
if [ ${f[4]} != 'None' ]; then
echo "SKIP PRESERVED RG: ${f[0]}"
else
cmd="time az group delete --no-wait -y --subscription '${subId}' -n '${f[0]}'"
echo $cmd
if [ $realRun == 1 ]; then
eval $cmd || : # Do not exit on error on deletion
fi
fi
else
echo "ACTIVITY DETECTED ON RG: ${f[0]}"
echo "${activities}"
fi
done
# reset IFS
IFS=$'\n'