-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkn
81 lines (63 loc) · 2.28 KB
/
kn
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
#!/bin/bash
# To use this script, invoke it like so: `. kn [namespace or namespace alias]`.
# You can also `alias kn='. kn'` and thereby invoke `kn [namespace or namespace alias]>`.
# The kubeconfigs generated by this script expect a base kubeconfig to
# define the cluster and user that it references.
KCKN_BASE_KUBECONFIG="${KCKN_BASE_KUBECONFIG:-${HOME}/.kube/config}"
KCKN_NAMESPACE_ALIASES="${KCKN_NAMESPACE_ALIASES}"
__kckn_kn_main() {
local cluster namespace user stub_kubeconfig stacked_kubeconfigs flattened_kubeconfig
if ! [[ -f "${KCKN_BASE_KUBECONFIG}" ]]; then
>&2 echo "Base kubeconfig does not exist: ${KCKN_BASE_KUBECONFIG}"
return 1
fi
namespace="${1:-default}"
if grep "^${namespace} " "${KCKN_NAMESPACE_ALIASES}" >/dev/null 2>&1; then
namespace="$(grep "^${namespace} " "${KCKN_NAMESPACE_ALIASES}" | awk '{print $2}')"
fi
cluster="${__KCKN_KUBE_CLUSTER}"
if [[ -z "${cluster}" ]]; then
>&2 echo "No cluster is currently set"
return 1
fi
if grep "^${cluster} " "${KCKN_CLUSTER_USERS}" >/dev/null 2>&1; then
user="$(grep "^${cluster} " "${KCKN_CLUSTER_USERS}" | awk '{print $2}')"
else
user="${cluster}"
fi
stub_kubeconfig="$(mktemp)"
cat <<KUBECONFIG > "${stub_kubeconfig}"
apiVersion: v1
kind: Config
contexts:
- context:
cluster: ${cluster}
user: ${user}
namespace: ${namespace}
name: ${cluster}/${namespace}
$(
if [[ "$namespace" == "default" ]]; then
cat <<DEFAULTCONTEXT
# for the default namespace, also define a context whose name doesn't
# include the namespace.
- context:
cluster: ${cluster}
user: ${user}
namespace: ${namespace}
name: ${cluster}
DEFAULTCONTEXT
fi
)
current-context: ${cluster}/${namespace}
KUBECONFIG
stacked_kubeconfigs="${stub_kubeconfig}:${KCKN_BASE_KUBECONFIG}"
flattened_kubeconfig="$(mktemp)"
KUBECONFIG="${stacked_kubeconfigs}" kubectl config view --flatten > "${flattened_kubeconfig}"
# shellcheck disable=SC2034 # Variable to be consumed by user, e.g. in PS1
export __KCKN="${cluster}/${namespace}"
# shellcheck disable=SC2034 # Variable to be consumed by user, e.g. in PS1
export __KCKN_KUBE_NAMESPACE="${namespace}"
# shellcheck disable=SC2034 # Variable to be consumed by user, e.g. in PS1
export KUBECONFIG="${flattened_kubeconfig}"
}
__kckn_kn_main "$@"