forked from HariSekhon/DevOps-Bash-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.envrc-kubernetes
63 lines (52 loc) · 1.99 KB
/
.envrc-kubernetes
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
#!/usr/bin/env bash
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2021-02-25 10:10:53 +0000 (Thu, 25 Feb 2021)
#
# https://github.com/HariSekhon/DevOps-Bash-tools
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish
#
# https://www.linkedin.com/in/HariSekhon
#
set -euo pipefail
[ -n "${DEBUG:-}" ] && set -x
# XXX: Edit this - hardcode for localized convenience
CONTEXT="${1:-MYCONTEXT}"
# if set will also set the namespace for extra convenience
NAMESPACE="${2:-}"
#NAMESPACE="jenkins"
tmpdir="/tmp/.kube"
mkdir -pv "$tmpdir"
default_kubeconfig="${HOME:-$(cd ~ && pwd)}/.kube/config"
original_kubeconfig="${KUBECONFIG:-$default_kubeconfig}"
# reload safety - do not source from new tmpdir - not necessary for direnv but useful for local sourcing tests
#if [[ "$original_kubeconfig" =~ $tmpdir ]]; then
# echo "ignoring \$KUBECONFIG=$original_kubeconfig, using default home location $default_kubeconfig"
# original_kubeconfig="$default_kubeconfig"
#fi
# isolate the kubernetes context to avoid a race condition affecting any other shells or scripts
# epoch is added because $$ and $PPID are direnv sub-processes and may be reused later, so using epoch to add uniqueness
epoch="$(date +%s)"
export KUBECONFIG="$tmpdir/config.${EUID:-${UID:-$(id -u)}}.$$.$epoch"
# load your real kube config to isolated staging area to source the context info
if [ -f "$original_kubeconfig" ]; then
cp "$original_kubeconfig" "$KUBECONFIG"
elif [ -f "$default_kubeconfig" ]; then
cp "$default_kubeconfig" "$KUBECONFIG"
elif [ -f "$PWD/.kube/config" ]; then
cp "$PWD/.kube/config" "$KUBECONFIG"
else
echo "WARNING: failed to find one of:
$original_kubeconfig
$default_kubeconfig
$PWD/.kube/config
" >&2
fi
kubectl config use-context "$CONTEXT"
if [ -n "${NAMESPACE:-}" ]; then
kubectl config set-context "$CONTEXT" --namespace "$NAMESPACE"
fi