Skip to content

Instantly share code, notes, and snippets.

@stigok
Last active August 26, 2020 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stigok/e9bd268d94498ec8addb9f8706d2f487 to your computer and use it in GitHub Desktop.
Save stigok/e9bd268d94498ec8addb9f8706d2f487 to your computer and use it in GitHub Desktop.
Select active Kubernetes configuration file for the current terminal session
#!/bin/bash
# Select active Kubernetes configuration file for the current terminal session.
#
# Usage:
# - Configure $all_configs variable in this file. It should be a directory
# containing kubectl configuration files.
# - Set $KUBECONFIG to the location of the symbolic link that will be created
# - Run this script
#
# This script is meant to be run using the following alias:
# alias kxx='export KUBECONFIG=$HOME/.kube/tmp_$(date +%s); kx'
#
# Dependencies:
# - https://github.com/junegunn/fzf
#
# Author: stigok, Mar 2020
set -eu
# Path to dir containing multiple configuration files
all_configs="$HOME/.kube/configs"
# Use name from first arugment if supplied
presel=${1:-""}
if [[ -n "$presel" && -f "$all_configs/$presel" ]]
then
selected="$all_configs/$presel"
else
# Let user find config by name using fzf
selected="$all_configs/$(find "$all_configs" -type f -printf '%f\n' | sort | fzf --ansi --no-preview --query="$presel")"
fi
# Symbolic link target for the selected file
target=${KUBECONFIG:-"$HOME/.kube/config"}
# Make sure we're not overwriting existing files
if [[ -e "$target" && ! -L "$target" ]]; then
>&2 echo "Error: $target exists, but is not a symbolic link. Not overwriting."
exit 1
fi
if [[ ! -r "$selected" ]]; then
>&2 echo "Error: selected file does not exist: $selected"
exit 1
fi
ln -sf "$selected" "$target"
basename "$selected"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment