-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkc
91 lines (72 loc) · 2.52 KB
/
kc
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
#!/bin/bash
# To use this script, invoke it like so: `. kc <cluster or cluster alias>`.
# You can also `alias kc='. kc'` and thereby invoke `kc <cluster or cluster 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_CLUSTER_ALIASES="${KCKN_CLUSTER_ALIASES}"
__kckn_kc_main() {
local cluster namespace user stub_kubeconfig stacked_kubeconfigs flattened_kubeconfig
if [[ "$1" == off ]]; then
unset KUBECONFIG
unset __KCKN_KUBE_CLUSTER
unset __KCKN_KUBE_NAMESPACE
unset __KCKN
return
fi
if [[ -z "$1" ]]; then
>&2 echo "You must specify a cluster or 'off'"
return 1
fi
if ! [[ -f "${KCKN_BASE_KUBECONFIG}" ]]; then
>&2 echo "Base kubeconfig does not exist: ${KCKN_BASE_KUBECONFIG}"
return 1
fi
cluster="$1"
if grep "^${cluster} " "${KCKN_CLUSTER_ALIASES}" >/dev/null 2>&1; then
cluster="$(grep "^${cluster} " "${KCKN_CLUSTER_ALIASES}" | awk '{print $2}')"
fi
namespace="${__KCKN_KUBE_NAMESPACE:-default}"
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_CLUSTER="${cluster}"
# 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_kc_main "$@"