Kubernetes cluster configuration extractor
/kubeconfig/extract-kubeconfig.sh
If you tend to work with lots of Kubernetes clusters, you’ll probably have
a ~/.kube/config
file full of cluster configurations, users and contexts.
Maybe at some point you have to extract entries for one particular context, for
example to share a cluster configuration with someone.
This script does that automatically. You just provide the name of the new
context you want to extract for this configuration and it outputs the minimal
YAML contents for a usable kubectl
configuration.
The name of the context is the only mandatory argument. Then you can pass up
an additional argument, which is the path to your kubectl
configuration file.
Default: ~/.kube/config
.
Finally, for extracting and merging the YAML entries, this script makes use of the
yq
tool from Mike Farah. You must download the single binary from the
releases page in GitHub and put it somewhere in your $PATH
. Don’t confuse
it with the yq
Python package: that’s just a wrapper around jq
and works in
a completely different way.
Download
this script
Secondary click/Save as…
#!/usr/bin/env bash
#
# extract-kubeconfig.sh
# Copyright 2020 eth0 <ethernet.zero@gmail.com>
#
# This work is free. You can redistribute it and/or modify it under the terms of
# the ISC License.
#
yq="$(command -v yq)"
if [[ -z "$yq" ]]; then
echo "$0: you need the yq tool, download it from https://github.com/mikefarah/yq/releases" >&2
exit 1
fi
if [[ ! "$1" ]]; then
echo "$0: you must specify a context name" >&2
exit 1
fi
context_name="$1"
kubeconfig=${2-~/.kube/config}
if [[ ! -f "$kubeconfig" ]]; then
echo "$0: $kubeconfig doesn't exist" >&2
exit 1
fi
kcexpr="$(printf '"%s" as $contextname |\n' "$context_name"; cat <<-'EOF'
(.contexts[] | select(.name == $contextname).context) as $context |
{
"apiVersion": "v1",
"kind": "Config",
"preferences": {},
"current-context": $contextname,
"contexts": [{"name": $contextname, "context": $context}],
"users": [.users[] | select(.name == $context.user)],
"clusters": [.clusters[] | select(.name == $context.cluster)]
}
EOF
)"
yq eval "$kcexpr" "$kubeconfig"