Skip to content

Commit d881942

Browse files
committed
feat(/usr/local/bin/k): Install kubectl just-in-time
See https://github.com/jakepearson/k
1 parent ebd84ed commit d881942

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ creating [issues][] and submitting [pull requests][].
2727
* [helm][]: Kubernetes package manager
2828
* [jq][]: command-line JSON processor
2929
* [jwt][]: tool for creating and parsing JSON Web Tokens
30+
* [k][]: automatically run the correct version of `kubectl` every time
3031
* [kubectl][]: Kubernetes command-line client
3132
* [Packer][]: build automated machine images
3233
* [ruby][]: ruby scripting language
@@ -83,6 +84,7 @@ The latest deis/go-dev Docker image is available at:
8384
[issues]: https://github.com/deis/docker-go-dev/issues
8485
[jq]: https://stedolan.github.io/jq/
8586
[jwt]: https://github.com/dgrijalva/jwt-go
87+
[k]: https://github.com/jakepearson/k
8688
[kubectl]: https://kubernetes.io/docs/user-guide/kubectl-overview/
8789
[pull requests]: https://github.com/deis/docker-go-dev/pulls
8890
[Quay.io]: https://quay.io

rootfs/usr/local/bin/k

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#!/usr/bin/env bash
2+
set +x
3+
4+
KX_PATH="$HOME/.kx"
5+
mkdir -p "$KX_PATH/cache"
6+
7+
case "$OSTYPE" in
8+
*arwin*)
9+
OS="darwin"
10+
;;
11+
*in32* | *indows*)
12+
OS="windows"
13+
;;
14+
*)
15+
OS="linux"
16+
esac
17+
18+
# Attempt to load the server version from cache
19+
if [ ! -z "$KUBECONFIG" ]; then
20+
if [ "$OS" == "darwin" ]; then
21+
KUBECONFIG_HASH=$(echo "$KUBECONFIG" | shasum -a 256 | cut -c1-5)
22+
else
23+
KUBECONFIG_HASH=$(echo "$KUBECONFIG" | sha256sum | cut -c1-5)
24+
fi
25+
VERSION_CACHE_FILE="$KX_PATH/cache/$KUBECONFIG_HASH"
26+
TARGET_VERSION=$(cat "$VERSION_CACHE_FILE" 2> /dev/null)
27+
fi
28+
29+
# Get the server version from the server if not cached
30+
if [ -z "$TARGET_VERSION" ]; then
31+
TARGET_VERSION=$(kubectl version -o json 2>/dev/null | jq -r '.serverVersion.gitVersion')
32+
fi
33+
34+
# Default to kubectl v1.10.12 if TARGET_VERSION was unset and `kubectl version` failed
35+
if [ "$TARGET_VERSION" == "null" ]; then
36+
TARGET_VERSION=v1.10.12
37+
fi
38+
39+
# Fill the cache if possible
40+
if [ ! -z "$KUBECONFIG" ]; then
41+
echo "$TARGET_VERSION" > "$VERSION_CACHE_FILE"
42+
fi
43+
44+
TARGET=$KX_PATH/kubectl-$TARGET_VERSION
45+
46+
if [ ! -f $TARGET ]; then
47+
cd "$KX_PATH"
48+
echo "Downloading kubectl $TARGET_VERSION..."
49+
curl -sLO "https://storage.googleapis.com/kubernetes-release/release/$TARGET_VERSION/bin/$OS/amd64/kubectl"
50+
mv $KX_PATH/kubectl $TARGET
51+
chmod +x $TARGET
52+
fi
53+
54+
$TARGET "$@"

0 commit comments

Comments
 (0)