Debian Codegraph @

kubens

raw
1 #!/usr/bin/env bash
2 #
3 # kubens(1) is a utility to switch between Kubernetes namespaces.
4
5 # Copyright 2017 Google Inc.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18
19 [[ -n $DEBUG ]] && set -x
20
21 set -eou pipefail
22 IFS=$'\n\t'
23
24 SELF_CMD="$0"
25
26 KUBENS_DIR="${XDG_CACHE_HOME:-$HOME/.kube}/kubens"
27
28 usage() {
29 local SELF
30 SELF="kubens"
31 if [[ "$(basename "$0")" == kubectl-* ]]; then # invoked as plugin
32 SELF="kubectl ns"
33 fi
34
35 cat <<EOF
36 Switch between Kubernetes namespaces.
37
38 USAGE:
39 $SELF : list the namespaces in the current context
40 $SELF <NAME> : change the active namespace of current context
41 $SELF - : switch to the previous namespace in this context
42 $SELF -c, --current : show the current namespace
43 $SELF -h,--help : show this message
44
45 (This executable is the legacy bash-based implementation, consider upgrading to Go-based implementation.)
46 EOF
47 }
48
49 exit_err() {
50 echo >&2 "${1}"
51 exit 1
52 }
53
54 current_namespace() {
55 local cur_ctx
56
57 cur_ctx="$(current_context)" || exit_err "error getting current context"
58 ns="$($KUBECTL config view -o=jsonpath="{.contexts[?(@.name==\"${cur_ctx}\")].context.namespace}")" \
59 || exit_err "error getting current namespace"
60
61 if [[ -z "${ns}" ]]; then
62 echo "default"
63 else
64 echo "${ns}"
65 fi
66 }
67
68 current_context() {
69 $KUBECTL config current-context
70 }
71
72 get_namespaces() {
73 $KUBECTL get namespaces -o=jsonpath='{range .items[*].metadata.name}{@}{"\n"}{end}'
74 }
75
76 escape_context_name() {
77 echo "${1//\//-}"
78 }
79
80 namespace_file() {
81 local ctx
82
83 ctx="$(escape_context_name "${1}")"
84 echo "${KUBENS_DIR}/${ctx}"
85 }
86
87 read_namespace() {
88 local f
89 f="$(namespace_file "${1}")"
90 [[ -f "${f}" ]] && cat "${f}"
91 return 0
92 }
93
94 save_namespace() {
95 mkdir -p "${KUBENS_DIR}"
96 local f saved
97 f="$(namespace_file "${1}")"
98 saved="$(read_namespace "${1}")"
99
100 if [[ "${saved}" != "${2}" ]]; then
101 printf %s "${2}" > "${f}"
102 fi
103 }
104
105 switch_namespace() {
106 local ctx="${1}"
107 $KUBECTL config set-context "${ctx}" --namespace="${2}"
108 echo "Active namespace is \"${2}\".">&2
109 }
110
111 choose_namespace_interactive() {
112 # directly calling kubens via fzf might fail with a cryptic error like
113 # "$FZF_DEFAULT_COMMAND failed", so try to see if we can list namespaces
114 # locally first
115 if [[ -z "$(list_namespaces)" ]]; then
116 echo >&2 "error: could not list namespaces (is the cluster accessible?)"
117 exit 1
118 fi
119
120 local choice
121 choice="$(_KUBECTX_FORCE_COLOR=1 \
122 FZF_DEFAULT_COMMAND="${SELF_CMD}" \
123 fzf --ansi --no-preview || true)"
124 if [[ -z "${choice}" ]]; then
125 echo 2>&1 "error: you did not choose any of the options"
126 exit 1
127 else
128 set_namespace "${choice}"
129 fi
130 }
131
132 set_namespace() {
133 local ctx prev
134 ctx="$(current_context)" || exit_err "error getting current context"
135 prev="$(current_namespace)" || exit_error "error getting current namespace"
136
137 if grep -q ^"${1}"\$ <(get_namespaces); then
138 switch_namespace "${ctx}" "${1}"
139
140 if [[ "${prev}" != "${1}" ]]; then
141 save_namespace "${ctx}" "${prev}"
142 fi
143 else
144 echo "error: no namespace exists with name \"${1}\".">&2
145 exit 1
146 fi
147 }
148
149 list_namespaces() {
150 local yellow darkbg normal
151 yellow=$(tput setaf 3 || true)
152 darkbg=$(tput setab 0 || true)
153 normal=$(tput sgr0 || true)
154
155 local cur_ctx_fg cur_ctx_bg
156 cur_ctx_fg=${KUBECTX_CURRENT_FGCOLOR:-$yellow}
157 cur_ctx_bg=${KUBECTX_CURRENT_BGCOLOR:-$darkbg}
158
159 local cur ns_list
160 cur="$(current_namespace)" || exit_err "error getting current namespace"
161 ns_list=$(get_namespaces) || exit_err "error getting namespace list"
162
163 for c in $ns_list; do
164 if [[ -n "${_KUBECTX_FORCE_COLOR:-}" || \
165 -t 1 && -z "${NO_COLOR:-}" ]]; then
166 # colored output mode
167 if [[ "${c}" = "${cur}" ]]; then
168 echo "${cur_ctx_bg}${cur_ctx_fg}${c}${normal}"
169 else
170 echo "${c}"
171 fi
172 else
173 echo "${c}"
174 fi
175 done
176 }
177
178 swap_namespace() {
179 local ctx ns
180 ctx="$(current_context)" || exit_err "error getting current context"
181 ns="$(read_namespace "${ctx}")"
182 if [[ -z "${ns}" ]]; then
183 echo "error: No previous namespace found for current context." >&2
184 exit 1
185 fi
186 set_namespace "${ns}"
187 }
188
189 main() {
190 if [[ -z "${KUBECTL:-}" ]]; then
191 if hash kubectl 2>/dev/null; then
192 KUBECTL=kubectl
193 elif hash kubectl.exe 2>/dev/null; then
194 KUBECTL=kubectl.exe
195 else
196 echo >&2 "kubectl is not installed"
197 exit 1
198 fi
199 fi
200
201 if [[ "$#" -eq 0 ]]; then
202 if [[ -t 1 && -z ${KUBECTX_IGNORE_FZF:-} && "$(type fzf &>/dev/null; echo $?)" -eq 0 ]]; then
203 choose_namespace_interactive
204 else
205 list_namespaces
206 fi
207 elif [[ "$#" -eq 1 ]]; then
208 if [[ "${1}" == '-h' || "${1}" == '--help' ]]; then
209 usage
210 elif [[ "${1}" == "-" ]]; then
211 swap_namespace
212 elif [[ "${1}" == '-c' || "${1}" == '--current' ]]; then
213 current_namespace
214 elif [[ "${1}" =~ ^-(.*) ]]; then
215 echo "error: unrecognized flag \"${1}\"" >&2
216 usage
217 exit 1
218 elif [[ "${1}" =~ (.+)=(.+) ]]; then
219 alias_context "${BASH_REMATCH[2]}" "${BASH_REMATCH[1]}"
220 else
221 set_namespace "${1}"
222 fi
223 else
224 echo "error: too many flags" >&2
225 usage
226 exit 1
227 fi
228 }
229
230 main "$@"