2020# management cluster which are not assigned to any instances.
2121#
2222# Usage and help:
23- # chmod +x cleanup-ag .sh
24- # ./cleanup-ag .sh -h
23+ # chmod +x cleanup-affinity-groups .sh
24+ # ./cleanup-affinity-groups .sh -h
2525
2626set -o errexit
2727set -o nounset
@@ -30,17 +30,19 @@ set -o pipefail
3030# script params
3131DRY_RUN=false
3232VERBOSE=false
33+
3334# k8s params
3435NAMESPACE=default
3536KUBECONFIG=$HOME /.kube/config
37+
3638# cmk params
3739CS_URL=
3840CS_APIKEY=
3941CS_SECRETKEY=
4042
4143debug () {
4244 if [[ " $VERBOSE " == " true" ]]; then
43- echo " [debug] $@ "
45+ echo -e " [debug] $@ "
4446 fi
4547}
4648
@@ -57,8 +59,8 @@ get_affinity_groups() {
5759}
5860
5961get_cluster () {
60- local affinityGroup =$1
61- _kubectl get cloudstackaffinitygroup $affinityGroup | jq -r ' .metadata.labels."cluster.x-k8s.io/cluster-name"'
62+ local affinitygroup =$1
63+ _kubectl get cloudstackaffinitygroup $affinitygroup | jq -r ' .metadata.labels."cluster.x-k8s.io/cluster-name"'
6264}
6365
6466get_cluster_credentials () {
@@ -75,20 +77,22 @@ setup_acs_credentials() {
7577}
7678
7779main () {
78- for ag in $( get_affinity_groups) ; do
79- echo " [info] Checking CloudStack Affinity Group: $ag "
80+ local ags=$( get_affinity_groups)
81+ debug " Affinity groups in the namespace $NAMESPACE :\n$ags "
82+ for ag in $ags ; do
83+ echo -e " \033[0;32m[info]\033[0m Checking CloudStack Affinity Group: $ag "
8084 local cluster=$( get_cluster $ag )
8185 for credential in $( get_cluster_credentials $cluster ) ; do
8286 setup_acs_credentials $credential
83- CS_AG_ID =$( _kubectl get cloudstackaffinitygroup $ag | jq -r ' .spec.id' )
84- CS_AG_VMS =$( _cmk list affinitygroups id=$CS_AG_ID | jq -r ' .affinitygroup[0].virtualmachineIds' )
85- if [[ " $CS_AG_VMS " == " null" ]]; then
86- echo " [ info] Found Affinity Group ($CS_AG_ID ) with no instances assigned:" $ag
87+ local ag_uuid =$( _kubectl get cloudstackaffinitygroup $ag | jq -r ' .spec.id' )
88+ local ag_instances =$( _cmk list affinitygroups id=$ag_uuid | jq -r ' .affinitygroup[0].virtualmachineIds' )
89+ if [[ " $ag_instances " == " null" ]]; then
90+ echo -e " \033[0;35m[ info]\033[0m Found Affinity Group ($ag_uuid ) with no instances assigned: $ag "
8791 if [[ " $DRY_RUN " == " false" ]]; then
8892 kubectl -n $NAMESPACE delete cloudstackaffinitygroup $ag
89- echo " [ info] Affinity Group ($CS_AG_ID ) $ag has been removed"
93+ echo -e " \033[0;31m[ info]\033[0m Affinity Group ($ag_uuid ) $ag has been removed"
9094 else
91- echo " [ dryrun] Affinity Group ($CS_AG_ID ) $ag has been removed"
95+ echo -e " \033[0;35m[info]\033[0m [ dryrun] Affinity Group ($ag_uuid ) $ag has been removed"
9296 fi
9397 fi
9498 done
@@ -115,7 +119,7 @@ help() {
115119 echo
116120}
117121
118- while getopts " :dkvh " option; do
122+ while getopts " :dk:vn:h " option; do
119123 case $option in
120124 d)
121125 DRY_RUN=true;;
0 commit comments