Skip to content

Instantly share code, notes, and snippets.

@rmkraus
Created September 10, 2023 07:28
Show Gist options
  • Save rmkraus/bab4ec25b031057e7f5e320bc1974031 to your computer and use it in GitHub Desktop.
Save rmkraus/bab4ec25b031057e7f5e320bc1974031 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -o errexit
if [ "$KUBECONFIG" == "" ]; then
KUBECONFIG=~/.kube/config
fi
echo "Kubeconfig file at: $KUBECONFIG"
gist_id_file="$(dirname $KUBECONFIG)/.$(basename $KUBECONFIG)-gist-id"
## CONNECT TO AN EXISTING GIST
if [ "$1" == "connect" ]; then
echo "Connecting to existing Kubeconfig gist."
if [ -f $KUBECONFIG ]; then
echo "Kubeconfig already exists. Plese remove it to continue." >&2
exit 1
fi
gist_id="$2"
if ! gh gist view "$gist_id" &> /dev/null; then
echo "Please provide a valid gist id." >&2
echo "Usage: kubectl sync connect GIST_ID" >&2
exit 2
fi
echo $gist_id > $gist_id_file
$0 pull
exit 0
fi
## CREATE A NEW GIST
if [ "$1" == "create" ]; then
echo "Creating a new Kubeconfig gist."
if [ ! -f $KUBECONFIG ]; then
echo "Please create a Kubeconfig file first." >&2
exit 3
fi
gist_id=$(gh gist create $KUBECONFIG)
echo -n $gist_id > $gist_id_file
echo "Kubeconfig has been pushed to Gist."
echo "Connect additional machines with the following command:"
echo " kubectl sync connect $gist_id"
exit 0
fi
## PULL THE CONFIG
if [ "$1" == "pull" ]; then
echo "Pulling remote kubeconfig from gist."
gist_id=$(cat $gist_id_file)
if ! gh gist view $gist_id &> /dev/null; then
echo "Gist does not appear to exist on remote." >&2
exit 4
fi
cp $KUBECONFIG $KUBECONFIG.sync-bkp &> /dev/null || echo
gh gist view $gist_id > $KUBECONFIG
exit 0
fi
## PUSH THE CONFIG
if [ "$1" == "push" ]; then
echo "Pushing local Kubeconfig to gist."
gist_id=$(cat $gist_id_file)
if ! gh gist view $gist_id &> /dev/null; then
echo "Gist does not appear to exist on remote." >&2
exit 4
fi
cat $KUBECONFIG | gh gist edit $gist_id -f $(basename $KUBECONFIG) -
exit 0
fi
## VIEW THE SAVED CONFIG
if [ "$1" == "view" ]; then
gist_id=$(cat $gist_id_file)
gh gist view $gist_id -f $(basename $KUBECONFIG)
exit 0
fi
echo """
Usage:
kubectl sync create # create a new remote kubeconfig with existing kubeconfig.
kubectl sync connect GIST-ID # setup machine to sync kubeconfig from specified gist
kubectl sync pull # pull the remote config to local machine
kubectl sync push # push the local config to remote
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment