-
Notifications
You must be signed in to change notification settings - Fork 7
/
kindadm
executable file
·401 lines (362 loc) · 14.7 KB
/
kindadm
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#!/usr/bin/env bash
set -eu
# default versions
HELM_VER='3.12.2'
export KINDADM_KIND_HELM_ENV='v3'
HELM_VER_3='3.12.2'
HELM_VER_2='2.17.0'
# define vars
K8S_VER="false"
OPT_APPS="false"
REG_CFG="false"
COEFFICIENT_LABEL="false"
COEFFICIENT_TAINT="false"
NODE_LABEL="false"
NODE_TAINT_LABEL="false"
LIGHT_GREEN='\033[1;32m'
LIGHT_RED='\033[1;31m'
NC='\033[0m' # No Color
SCRIPT_DIR="$( cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 ; pwd -P )"
CACHE_DIR="$SCRIPT_DIR/.cache"
EXEC_DIR="$CACHE_DIR"
KIND_CFG="$(<"$SCRIPT_DIR"/templates/kind-base-config.yaml)" # base config file
K8S_CLUSTERS="$("$EXEC_DIR"/kind get clusters 2>/dev/null | tr '\n' ' ' | sed 's/[[:blank:]]*$//')"
SUPPORTED_OPT_APPS="$(ls -d "$SCRIPT_DIR"/helmfiles/apps/optional/*/ | rev | cut -f2 -d'/' | rev)"
NO_NODES='1'
REG_NAME='kind-registry'
SETUP_EXEC="$SCRIPT_DIR"/bin/setup.sh
SYS_WIDE=false
# predefined functions
function contains_string {
local list="$1"
local item="$2"
if [[ "$list" =~ (^|[[:space:]])"$item"($|[[:space:]]) ]]; then
# yes, list includes item
result=0
else
result=1
fi
return "$result"
}
function contains_strings_from_strings {
local list_a="$1"
local list_b="$2"
for str in "$list_a"; do
if [[ "$list_b" =~ (^|,)"$str"(,|$) ]]; then
# yes, list includes item
result=0
else
result=1
break
fi
done
return "$result"
}
function create_k8s_ns {
# create required K8s namespaces for apps
if [[ "$1" == 'all' ]]; then
local k8s_ns=($(grep -r 'namespace: ' "$SCRIPT_DIR"/helmfiles/apps/optional/*/helmfile-"$KINDADM_KIND_HELM_ENV".yaml | cut -d ':' -f2 | tr -d ' '))
elif [[ "$1" != 'all' ]] && [[ "$1" != 'default' ]]; then
local k8s_ns=($(grep 'namespace: ' "$SCRIPT_DIR"/helmfiles/apps/optional/"$1"/helmfile-"$KINDADM_KIND_HELM_ENV".yaml | cut -d ':' -f2 | tr -d ' '))
else
local k8s_ns=($(grep -r 'namespace: ' "$SCRIPT_DIR"/helmfiles/apps/default/*/helmfile-"$KINDADM_KIND_HELM_ENV".yaml | cut -d ':' -f3 | tr -d ' '))
fi
local unique_k8s_ns=($(tr ' ' '\n' <<< "${k8s_ns[@]}" | tr '\n' ' '))
for ((i=0;i<"${#unique_k8s_ns[@]}";i++)); do
if [[ -n "${unique_k8s_ns[i]}" ]] ; then
set +e; kubectl create namespace "${unique_k8s_ns[i]}" 2>/dev/null; set -e
else
break
fi
done
}
# Custom `select` implementation that allows *empty* input.
function selectWithDefault {
local item i=0 numItems=$#
# Print numbered menu items, based on the arguments passed.
for item; do # Short for: for item in "$@"; do
printf '%s\n' "$((++i))) $item"
done >&2 # Print to stderr, as `select` does.
# Prompt the user for the index of the desired item.
while :; do
printf %s "${PS3-#? }" >&2 # Print the prompt string to stderr, as `select` does.
read -r index
# Make sure that the input is either empty or that a valid index was entered.
[[ -z $index ]] && index=1 # empty input
(( index >= 1 && index <= numItems )) 2>/dev/null || { echo "Invalid selection. Please try again." >&2; continue; }
break
done
# Output the selected item, if any.
[[ -n $index ]] && printf %s "${@: index:1}"
}
function purge_clusters {
echo -e "Purge ALL clusters or PER cluster (default: ${LIGHT_GREEN}'ALL'${NC})?"
optionsPurge=('ALL' 'PER')
choice="$(selectWithDefault "${optionsPurge[@]}")"
# Process the selected item.
case "$choice" in
''|'ALL' ) echo -e "${LIGHT_GREEN}${choice}${NC}";
IFS='\n' declare -g clusters=(${K8S_CLUSTERS});
;;
'PER' ) echo -e "${LIGHT_GREEN}${choice}${NC}";
echo "Which cluster to purge?";
read -p "[ ${K8S_CLUSTERS} ]: " K8S_CLUSTER;
if ! `contains_string "${K8S_CLUSTERS}" "$K8S_CLUSTER"`; then
echo "Invalid cluster name."
exit 3
fi
declare -g clusters=("$K8S_CLUSTER");
;;
esac
}
function create_reg {
# create registry container
running="$(docker inspect -f '{{.State.Running}}' "${REG_NAME}" 2>/dev/null || true)"
if [ "${running}" != 'true' ]; then
docker run \
-d --restart=always -p "${REG_PORT}:5000" --name "${REG_NAME}" \
registry:2 >/dev/null
echo -e "\n${LIGHT_GREEN}\u2713${NC} Docker Container Registry - ${LIGHT_GREEN}started${NC}.\n"
fi
}
function rm_reg {
# conditionally remove registry container
running="$(docker inspect -f '{{.State.Running}}' "${REG_NAME}" 2>/dev/null || true)"
echo -e "\nPurge the local Container Registry for K8s cluster(s) (default: ${LIGHT_GREEN}'YES'${NC})?"
optionsRmReg=('YES' 'NO')
choice="$(selectWithDefault "${optionsRmReg[@]}")"
# Process the selected item.
case "$choice" in
''|'YES' ) echo -e "${LIGHT_GREEN}${choice}${NC}";
if [ "${running}" == 'true' ]; then
docker rm -f "${REG_NAME}" >/dev/null
echo -e "${LIGHT_GREEN}\u2713${NC} Local Container Registry - ${LIGHT_GREEN}purged${NC}."
else
echo -e "${LIGHT_RED}\u2717${NC} No local registry found."
fi
;;
'NO' ) echo -e "${LIGHT_RED}${choice}${NC}";
;;
esac
}
function conn_to_kind_netw {
CONTAINERS=$(docker network inspect kind -f "{{range .Containers}}{{.Name}} {{end}}")
NEEDS_CONNECT="true"
for c in $CONTAINERS; do
if [ "$c" = "${REG_NAME}" ]; then
NEEDS_CONNECT="false"
fi
done
if [ "${NEEDS_CONNECT}" == "true" ]; then
docker network connect kind "${REG_NAME}" 2>/dev/null || true
fi
}
while [ $# -gt 0 ]; do
case "$1" in
--nodes=*|-n=*)
if [[ "$1" != *=[1-9] ]] && [[ "$1" != *=[1-9][1-9] ]]; then
printf "\nNo. of K8s nodes must be: ${LIGHT_GREEN}1-99${NC}.\n"
exit 5
fi
NO_NODES="${1#*=}"
;;
--all-labelled=*|-al=*)
NODE_LABEL="${1#*=}"
COEFFICIENT_LABEL=1
;;
--half-labelled=*|-hl=*)
NODE_LABEL="${1#*=}"
COEFFICIENT_LABEL=0.5
;;
--all-tainted=*|-at=*|--all-tainted|-at)
if [[ "$1" == *=* ]]; then NODE_TAINT_LABEL="${1#*=}"; fi
COEFFICIENT_TAINT=1
;;
--half-tainted=*|-ht=*|--half-tainted|-ht)
if [[ "$1" == *=* ]]; then NODE_TAINT_LABEL="${1#*=}"; fi
COEFFICIENT_TAINT=0.5
;;
--opt-apps=*|-oa=*)
if [[ "$1" == *=all ]]; then
OPT_APPS=all
else
OPT_APPS="${1#*=}"
if ! `contains_strings_from_strings "$SUPPORTED_OPT_APPS" "$OPT_APPS"`; then
printf "\nSupported optional apps (comma-separated): ${LIGHT_GREEN}"$SUPPORTED_OPT_APPS"${NC}.\n"
exit 6
fi
fi
;;
--k8s_ver=*|-v=*)
# declare -A k8s_vers_avail="$(wget -q https://registry.hub.docker.com/v1/repositories/kindest/node/tags -O - | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | tr '}' '\n' | awk -F: '{print $3}' | tr -d 'v')"
declare -A k8s_vers_avail="$(wget -q https://registry.hub.docker.com/v2/repositories/kindest/node/tags?page_size=100 -O - | jq '."results"[]["name"]' )"
if ! [[ "${k8s_vers_avail[@]}" =~ "${1#*=}" ]]; then
printf "\nUnsupported K8s node version.\nSupported versions:\n"
printf '%s\n' "${k8s_vers_avail[*]}" | paste -sd ','
exit 7
fi
K8S_VER="${1#*=}"
;;
--purge|-p)
purge_clusters
for ((i=0;i<"${#clusters[@]}";i++)); do
"$EXEC_DIR"/kind delete cluster --name "${clusters[i]}"
done
printf "\n${LIGHT_GREEN}Clusters left:${NC}\n"
"$EXEC_DIR"/kind get clusters
rm_reg
exit 0
;;
--list-oa|-loa)
printf "\nList of supported optional apps:\
\n ${LIGHT_GREEN}$SUPPORTED_OPT_APPS${NC}\n"
exit 0
;;
--create-registry|-cr)
REG_PORT='5000'
REG_CFG="$(<"$SCRIPT_DIR"/templates/registry/kind-reg-cfg-patches.yaml)" # Local Registry KinD patches
;;
--helm_ver=*|-hv=*)
if [[ "$1" != *=2 ]] && [[ "$1" != *=2.*.* ]] && [[ "$1" != *=3 ]] && [[ "$1" != *=3.*.* ]]; then
printf "\nIncompatible Helm ver.\nSupported syntax/version: ${LIGHT_GREEN}2${NC} / ${LIGHT_GREEN}3${NC} / ${LIGHT_GREEN}2.[x].[x]${NC} / ${LIGHT_GREEN}3.[x].[x]${NC}\n"
exit 1
else
if [[ "$1" == *=3.*.* ]] || [[ "$1" == *=2.*.* ]]; then HELM_VER="${1#*=}"
elif [[ "$1" == *=3 ]]; then HELM_VER="$HELM_VER_3"
elif [[ "$1" == *=2 ]]; then HELM_VER="$HELM_VER_2"; fi
fi
;;
--sys_wide|-sw)
printf "\nInstalling prerequisites ${LIGHT_GREEN}system-wide${NC}.\n"
SYS_WIDE=true
EXEC_DIR='/usr/local/bin'
;;
--help|-h)
printf "\nUsage:\
\n ${LIGHT_GREEN}--all-labelled,-al${NC} Set labels on all K8s nodes.\
\n ${LIGHT_GREEN}--all-tainted,-at${NC} Set taints on all K8s nodes. A different label can be defined.\
\n ${LIGHT_GREEN}--create-registry,-cr${NC} Create local container registry for K8s cluster(s).\
\n ${LIGHT_GREEN}--half-labelled,-hl${NC} Set labels on half K8s nodes.\
\n ${LIGHT_GREEN}--half-tainted,-ht${NC} Set taints on half K8s nodes. A different label can be defined.\
\n ${LIGHT_GREEN}--helm_ver,-hv${NC} Set Helm version to be installed.\
\n ${LIGHT_GREEN}--k8s_ver,-v${NC} Set K8s version to be deployed.\
\n ${LIGHT_GREEN}--list-oa,-loa${NC} List supported optional app(s).\
\n ${LIGHT_GREEN}--nodes,-n${NC} Set number of K8s nodes to be created.\
\n ${LIGHT_GREEN}--opt-apps,-oa${NC} Deploy supported optional app(s).\
\n ${LIGHT_GREEN}--purge,-p${NC} Purge interactively any existing cluster(s) and related resources.\
\n ${LIGHT_GREEN}--sys_wide,-sw${NC} Install prerequisites system-wide.\
\n ${LIGHT_GREEN}--help,-h${NC} Prints this message.\
\nExample:\n ${LIGHT_GREEN}kindadm -n=2 -v=1.19.1 -hl='nodeType=devops' -ht -oa=weave-scope -cr -hv=2 -sw${NC}\n" # Flag argument
exit 0
;;
*)
>&2 printf "\nError: ${LIGHT_RED}Invalid argument${NC}\n"
exit 8
;;
esac
shift
done
# validate definitions of req. variables
if [[ "$COEFFICIENT_TAINT" != 'false' ]]; then
if [[ "$NODE_LABEL" == 'false' && "$NODE_TAINT_LABEL" == 'false' ]] ; then
printf "\nError: ${LIGHT_RED}Specify node or taint label.${NC}\n"
exit 11
fi
fi
# set up prereqs
bash "$SETUP_EXEC" "$HELM_VER" "$SYS_WIDE" "$CACHE_DIR" "$EXEC_DIR"
if [[ "$K8S_VER" == 'false' ]]; then
KIND_CTRL_CFG=$'\n - role: control-plane\n extraMounts:\n - hostPath: /var/run/docker.sock\n containerPath: /var/run/docker.sock'
KIND_WRKR_CFG=$'\n - role: worker\n extraMounts:\n - hostPath: /var/run/docker.sock\n containerPath: /var/run/docker.sock'
else
KIND_CTRL_CFG=$'\n - role: control-plane\n image: kindest/node:v'"${K8S_VER}"$'\n extraMounts:\n - hostPath: /var/run/docker.sock\n containerPath: /var/run/docker.sock'
KIND_WRKR_CFG=$'\n - role: worker\n image: kindest/node:v'"${K8S_VER}"$'\n extraMounts:\n - hostPath: /var/run/docker.sock\n containerPath: /var/run/docker.sock'
fi
# Adjust KinD config
## Calculate no. of nodes
if [ "${NO_NODES}" == 1 ]; then
NO_NODES_CREATE="$((${NO_NODES} - 1))"
else
NO_NODES_CREATE="${NO_NODES}"
fi
## Create new KinD config
KIND_CFG="${KIND_CFG}${KIND_CTRL_CFG}"
for (( i=0; i<"${NO_NODES_CREATE}"; ++i));
do
KIND_CFG="${KIND_CFG}${KIND_WRKR_CFG}"
done
if [[ "$REG_CFG" != 'false' ]]; then
KIND_CFG="${KIND_CFG}${REG_CFG}"
fi
# Create KinD cluster
"$EXEC_DIR"/kind create cluster --config <(echo "${KIND_CFG}") --name kind-"${NO_NODES}"
# Get node names
CLUSTER_WRKS=$("$EXEC_DIR"/kubectl get nodes | tail -n +2 | cut -d' ' -f1)
IFS=$'\n' CLUSTER_WRKS=(${CLUSTER_WRKS})
# Put node labels
if [[ "$COEFFICIENT_LABEL" != 'false' ]]; then
NO_NODES_LABELLED="$(bc -l <<<"${#CLUSTER_WRKS[@]} * $COEFFICIENT_LABEL" | awk '{printf("%d\n",$1 + 0.5)}')"
for ((i=1;i<="$NO_NODES_LABELLED";i++)); do
"$EXEC_DIR"/kubectl label node "${CLUSTER_WRKS[(i-1)]}" "$NODE_LABEL" >/dev/null 2>&1
done
echo -e "\n${LIGHT_GREEN}\u2713${NC} Cluster nodes - ${LIGHT_GREEN}labelled${NC}."
fi
# Taint nodes with "NoExecute"
if [[ "$COEFFICIENT_TAINT" != 'false' ]]; then
NO_NODES_TAINTED="$(bc -l <<<"${#CLUSTER_WRKS[@]} * $COEFFICIENT_TAINT" | awk '{printf("%d\n",$1 + 0.5)}')"
for ((i=1;i<="$NO_NODES_TAINTED";i++)); do
if [[ "$NODE_TAINT_LABEL" == 'false' ]] ; then
"$EXEC_DIR"/kubectl taint node "${CLUSTER_WRKS[(i-1)]}" "$NODE_LABEL":NoExecute >/dev/null 2>&1
else
"$EXEC_DIR"/kubectl taint node "${CLUSTER_WRKS[(i-1)]}" "$NODE_TAINT_LABEL":NoExecute >/dev/null 2>&1
fi
done
echo -e "\n${LIGHT_GREEN}\u2713${NC} Cluster nodes - ${LIGHT_GREEN}tainted${NC}."
fi
if [[ "$REG_CFG" != 'false' ]]; then
create_reg
"$EXEC_DIR"/kubectl apply -f "$SCRIPT_DIR"/templates/registry/kind-reg-configmap.yaml >/dev/null 2>&1
conn_to_kind_netw
fi
if [[ "$HELM_VER" == 2.*.* ]]; then
# Set Helm var for helmfile
export KINDADM_KIND_HELM_ENV='v2'
# Adjust Tiller K8s permissions
"$EXEC_DIR"/kubectl create serviceaccount --namespace kube-system tiller >/dev/null 2>&1
"$EXEC_DIR"/kubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller >/dev/null 2>&1
# Init Helm
"$EXEC_DIR"/helm init --service-account tiller
# check Tiller readiness
set +e; echo -e '\nWaiting for Tiller to become ready...'; sleep 15
"$EXEC_DIR"/helm list >/dev/null 2>&1
while [ $? -ne 0 ] ; do
echo 'Another 15 sec...'
sleep 15
"$EXEC_DIR"/helm list >/dev/null 2>&1
done
set -e
echo -e "\n${LIGHT_GREEN}\u2713${NC} Tiller Server - ${LIGHT_GREEN}deployed and ready${NC}."
fi
# Get KinD network
export KINDADM_KIND_NETW_SHORT=$(docker network inspect kind -f "{{(index .IPAM.Config 0).Subnet}}" | cut -d '.' -f1,2)
# Deploy default apps
echo -e "\n${LIGHT_GREEN}Deploying default apps...${NC}"
create_k8s_ns "default"
"$EXEC_DIR"/helmfile -b "$EXEC_DIR"/helm -f "$SCRIPT_DIR"/helmfiles/apps/default/helmfile.yaml apply --concurrency 1 > /dev/null
echo -e "${LIGHT_GREEN}\u2713${NC} Default apps - ${LIGHT_GREEN}deployed${NC}."
# Deploy Kubernetes Dashboard Admin ClusterRoleBinding
"$EXEC_DIR"/kubectl apply -f "$SCRIPT_DIR"/templates/k8s-dashboard-rolebinding.yaml >/dev/null 2>&1
# Deploy conditionally optional apps
if [[ "$OPT_APPS" != 'false' ]]; then
echo -e "\n${LIGHT_GREEN}Deploying optional apps...${NC}"
if [[ "$OPT_APPS" == "all" ]]; then
create_k8s_ns "$OPT_APPS"
"$EXEC_DIR"/helmfile -b "$EXEC_DIR"/helm -f "$SCRIPT_DIR"/helmfiles/apps/optional/helmfile.yaml apply --concurrency 1 > /dev/null
else
for app in "$OPT_APPS"; do
create_k8s_ns "$app"
"$EXEC_DIR"/helmfile -b "$EXEC_DIR"/helm -f "$SCRIPT_DIR"/helmfiles/apps/optional/"$app"/helmfile-"$KINDADM_KIND_HELM_ENV".yaml apply --concurrency 1 > /dev/null
done
fi
echo -e "${LIGHT_GREEN}\u2713${NC} Optional apps - ${LIGHT_GREEN}deployed${NC}."
fi