Skip to content

Commit c3ebc22

Browse files
committed
Adds kns
1 parent ca117b1 commit c3ebc22

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

bin/kns

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env bash
2+
#
3+
usage() { # {{{
4+
cat <<-EOT
5+
Usage: $(basename "$0") <options> NAMESPACE
6+
Options:
7+
-c Just print current ns
8+
-l List all namespaces
9+
-h Show help / usage
10+
EOT
11+
} # }}}
12+
13+
14+
while getopts :hcl opt # {{{
15+
do
16+
case $opt in
17+
c)
18+
current_ns=$(kubectl config view --minify=true -o jsonpath="{..context.namespace}")
19+
printf "%s\n" "$current_ns"
20+
exit 0
21+
;;
22+
l)
23+
kubectl get ns -o json | jq '.items[].metadata.name' -r | sort
24+
exit 0
25+
;;
26+
h)
27+
usage
28+
exit
29+
;;
30+
:)
31+
printf "Option '%s' requires an argument\n" "${OPTARG}" >&2
32+
usage >&2
33+
exit 28
34+
;;
35+
?)
36+
printf "Invalid option '%s'\n" "${OPTARG}" >&2
37+
usage >&2
38+
exit 27
39+
;;
40+
esac
41+
done # }}}
42+
shift $((OPTIND-1))
43+
44+
current_ns=$(kubectl config view --minify=true -o jsonpath="{..context.namespace}")
45+
: "${current_ns:=default}"
46+
if [ $# -eq 0 ]
47+
then
48+
echo "Current namespace: '$current_ns'. Pass a namespace name to this command to set a new namespace" >&2
49+
exit
50+
fi
51+
ns=$1
52+
if [ "$current_ns" = "$ns" ]
53+
then
54+
echo "Namespace already set to $ns" >&2
55+
exit
56+
fi
57+
if ! kubectl get ns "$ns"
58+
then
59+
echo "No namespace exists with the name '$ns'" >&2
60+
exit
61+
fi
62+
kubectl config set-context --current --namespace="$ns"
63+
echo "Setting context to ${ns:-default}"

0 commit comments

Comments
 (0)