Skip to content

Commit

Permalink
writing temporary kubeconfig files and adding a cleanup command
Browse files Browse the repository at this point in the history
  • Loading branch information
danielfoehrKn committed Jun 14, 2020
1 parent 0470b54 commit 92502e1
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 19 deletions.
30 changes: 21 additions & 9 deletions cmd/switcher/switch.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (
)

var (
kubeconfigDir string
kubeconfigName string
showPreview bool
cmd = &cobra.Command{
kubeconfigDir string
kubeconfigName string
showPreview bool
rootCommand = &cobra.Command{
Use: "switch",
Short: "Launch the kubeconfig switcher",
Long: `Simple tool for switching between kubeconfig files.`,
Expand All @@ -22,23 +22,35 @@ var (
}
)

func init() {
deleteCmd := &cobra.Command{
Use: "clean",
Short: "Cleans all temporary kubeconfig files",
Long: `Cleans the temporary kubeconfig files created in the directory $HOME/.kube/switch_tmp`,
RunE: func(cmd *cobra.Command, args []string) error {
return pkg.Clean()
},
}
rootCommand.AddCommand(deleteCmd)
}

func NewCommandStartSwitcher() *cobra.Command {
return cmd
return rootCommand
}

func init() {
cmd.Flags().StringVar(
rootCommand.Flags().StringVar(
&kubeconfigDir,
"kubeconfig-directory",
os.ExpandEnv("$HOME/.kube/switch"),
os.ExpandEnv("$HOME/.kube"),
"directory containing the kubeconfig files.")

cmd.Flags().StringVar(
rootCommand.Flags().StringVar(
&kubeconfigName,
"kubeconfig-name",
"config",
"only shows kubeconfig files with exactly this name.")
cmd.Flags().BoolVar(
rootCommand.Flags().BoolVar(
&showPreview,
"show-preview",
true,
Expand Down
14 changes: 13 additions & 1 deletion hack/switch/switch.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
usage()
{
echo "Usage:"
echo -e " --kubeconfig-directory directory containing the kubeconfig files. Default is $HOME/.kube/switch"
echo -e " --kubeconfig-directory directory containing the kubeconfig files. Default is $HOME/.kube"
echo -e " --kubeconfig-name only shows kubeconfig files with exactly this name. Defaults to 'config'."
echo -e " --executable-path path to the 'switch' executable. If unset tries to use 'switch' from the path."
echo -e " --show-preview if it should show a preview. Preview is sanitized from credentials. Defaults to true."
echo -e " --help shows available flags."
echo -e " clean removes all the temporary kubeconfig files created in the directory $HOME/.kube/switch_tmp."
}

switch(){
Expand All @@ -19,6 +20,7 @@ switch(){
KUBECONFIG_NAME=''
EXECUTABLE_PATH=''
SHOW_PREVIEW=''
CLEAN=''

while test $# -gt 0; do
case "$1" in
Expand All @@ -42,6 +44,10 @@ switch(){
SHOW_PREVIEW=$1
shift
;;
clean)
CLEAN=$1
shift
;;
--help)
usage
return
Expand Down Expand Up @@ -83,6 +89,12 @@ switch(){
EXECUTABLE_PATH=$DEFAULT_EXECUTABLE_PATH
fi

if [ -n "$CLEAN" ]
then
$EXECUTABLE_PATH clean
return
fi

# execute golang binary handing over all the flags
NEW_KUBECONFIG=$($EXECUTABLE_PATH $KUBECONFIG_DIRECTORY_FLAG ${KUBECONFIG_DIRECTORY} $KUBECONFIG_NAME_FLAG ${KUBECONFIG_NAME} $SHOW_PREVIEW_FLAG ${SHOW_PREVIEW})
if [[ "$?" = "0" ]]; then
Expand Down
18 changes: 18 additions & 0 deletions pkg/clean.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package pkg

import (
"fmt"
"io/ioutil"
"os"
)

func Clean() error {
tempDir := os.ExpandEnv(temporaryKubeconfigDir)
files,_ := ioutil.ReadDir(tempDir)
err := os.RemoveAll(tempDir)
if err != nil {
return err
}
fmt.Printf("Cleaned %d files.", len(files))
return nil
}
35 changes: 26 additions & 9 deletions pkg/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (

const separator = "/"
const kubeconfigCurrentContext = "current-context:"
const temporaryKubeconfigDir = "$HOME/.kube/.switch_tmp"

func Switcher(kubeconfigDirectory, kubeconfigName string, showPreview bool) error {
kubeconfigPaths, err := findFilePathsInDirectory(kubeconfigDirectory, kubeconfigName)
Expand Down Expand Up @@ -81,20 +82,21 @@ func Switcher(kubeconfigDirectory, kubeconfigName string, showPreview bool) erro
log.Fatal(err)
}

// map selection back to Kubeconfig
// map selection back to kubeconfig
selectedContext := allKubeconfigContextNames[idx]
kubeconfigPath := contextToPathMapping[selectedContext]

// remove the folder name from the context name
split := strings.Split(selectedContext, separator)
selectedContext = split[len(split)-1]

if err := setCurrentContext(kubeconfigPath, selectedContext); err != nil {
tempKubeconfigPath, err := setCurrentContext(kubeconfigPath, selectedContext)
if err != nil {
log.Fatalf("failed to write current context to kubeconfig: %v", err)
}

// print kubeconfig path to std.out -> captured by calling bash script to set KUBECONFIG ENV Variable
fmt.Print(kubeconfigPath)
fmt.Print(tempKubeconfigPath)

return nil
}
Expand Down Expand Up @@ -135,7 +137,7 @@ func getContextNames(config *types.KubeConfig, parentFoldername string) []string
return contextNames
}

func setCurrentContext(kubeconfigPath, ctxnName string) error {
func setCurrentContext(kubeconfigPath string, ctxnName string) (string, error) {
currentContext := fmt.Sprintf("%s %s", kubeconfigCurrentContext, ctxnName)

input, err := ioutil.ReadFile(kubeconfigPath)
Expand All @@ -153,16 +155,31 @@ func setCurrentContext(kubeconfigPath, ctxnName string) error {
}
}

if !foundCurrentContext {
return appendCurrentContext(kubeconfigPath, currentContext)
output := strings.Join(lines, "\n")
tempDir := os.ExpandEnv(temporaryKubeconfigDir)
err = os.Mkdir(tempDir, 0700)
if err != nil && !os.IsExist(err) {
log.Fatalln(err)
}

output := strings.Join(lines, "\n")
err = ioutil.WriteFile(kubeconfigPath, []byte(output), 0644)
// write temporary kubeconfig file
file, err := ioutil.TempFile(tempDir, "config.*.tmp")
if err != nil {
log.Fatalln(err)
}
return nil

_, err = file.Write([]byte(output))
if err != nil {
log.Fatalln(err)
}

// if written file does not have the current context set,
// add the context at the last line of the file
if !foundCurrentContext {
return file.Name(), appendCurrentContext(file.Name(), currentContext)
}

return file.Name(), nil
}

func appendCurrentContext(kubeconfigPath, currentContext string) error {
Expand Down

0 comments on commit 92502e1

Please sign in to comment.