Skip to content

Instantly share code, notes, and snippets.

@dragonde
Last active August 2, 2024 15:28
Show Gist options
  • Save dragonde/2d39eea49a037d16b8a1cad2a46a3aee to your computer and use it in GitHub Desktop.
Save dragonde/2d39eea49a037d16b8a1cad2a46a3aee to your computer and use it in GitHub Desktop.
add-kubeconfig

add-kubeconfig

function add-kubeconfig() {
  if [[ -z $1 ]]; then
    echo "Usage: add-kubeconfig <path-to-kubeconfig>"
    return 1
  fi

  CONTEXT=$(yq e '.contexts[0].name' $1)
  if [[ $CONTEXT == null ]]; then
     echo "File $1 seems not to be a valid kubeconfig"
     return 1
  fi

  if yq e '.contexts[].name' ~/.kube/config | grep -P "^$CONTEXT$" > /dev/null; then
    echo "Context $CONTEXT already exists in ~/.kube/config"
    return 1
  fi

  echo ADDING $CONTEXT TO ~/.kube/config
  export KUBECONFIG="$HOME/.kube/config:$1"
  kubectl config view --flatten > /tmp/kubeconfig
  unset KUBECONFIG
  mv /tmp/kubeconfig ~/.kube/config
  chmod 0600 ~/.kube/config

  kubectl config use-context $CONTEXT
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment