-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubetool
executable file
·107 lines (96 loc) · 2.55 KB
/
kubetool
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
#!/bin/sh
[[ -n $DEBUG ]] && set -x
set -eou pipefail
usage() {
cat <<"EOF"
USAGE:
kubetool : show this message
kubetool ctx get : gets the current context
kubetool ctx set NAME : sets the current context
kubetool ctx ls,list : lists all of the contexts
kubetool ctx rename OLD NEW : renames a context from the old value to the new valud
kubetool ns get : get the current namespace for the current context
kubetool ns set NAME : set the current namespace for the current context
kubetool ns ls,list : list all namespaces for the current context
kubetool -h,--help : show this message
EOF
exit 1
}
list_contexts() {
kubectl config get-contexts -o=name | sort -n
}
get_context() {
kubectl config view -o=jsonpath='{.current-context}'
}
set_context() {
kubectl config use-context "${1}"
}
rename_context() {
local ctx
if [[ "${1}" == "." ]]; then
ctx="$(get_context)"
else
ctx="${1}"
fi
kubectl config rename-context "${ctx}" "${2}"
}
list_namespaces() {
kubectl get namespaces -o=jsonpath='{range .items[*].metadata.name}{@}{"\n"}{end}'
}
get_namespace() {
local ctx
ctx="$(get_context)"
ns="$(kubectl config view -o=jsonpath="{.contexts[?(@.name==\"${ctx}\")].context.namespace}")"
if [[ -z "${ns}" ]]; then
echo "default"
else
echo "${ns}"
fi
}
set_namespace() {
local ctx
ctx="$(get_context)"
kubectl config set-context "${ctx}" --namespace="${1}"
}
main() {
if [[ "$#" -eq 0 ]]; then
usage
elif [[ "${1}" == '-h' || "${1}" == '--help' ]]; then
usage
elif [[ "${1}" == "ns" ]]; then
if [[ "$#" -eq 2 && "${2}" == "get" ]]; then
get_namespace
elif [[ "$#" -eq 2 && "${2}" == "ls" ]]; then
list_namespaces
elif [[ "$#" -eq 2 && "${2}" == "list" ]]; then
list_namespaces
elif [[ "$#" -eq 3 && "${2}" == "set" ]]; then
set_namespace "${3}"
else
echo "error: invalid arguments" >&2
usage
exit 1
fi
elif [[ "${1}" == "ctx" ]]; then
if [[ "$#" -eq 2 && "${2}" == "get" ]]; then
get_context
elif [[ "$#" -eq 2 && "${2}" == "ls" ]]; then
list_contexts
elif [[ "$#" -eq 2 && "${2}" == "list" ]]; then
list_contexts
elif [[ "$#" -eq 3 && "${2}" == "set" ]]; then
set_context "${3}"
elif [[ "$#" -eq 4 && "${2}" == "rename" ]]; then
rename_context "${3}" "${4}"
else
echo "error: invalid arguments" >&2
usage
exit 1
fi
else
echo "error: invalid arguments" >&2
usage
exit 1
fi
}
main "$@"