Skip to content

Commit e0ac224

Browse files
bug: do not overwrite kubeconfig on error (#33)
if k0sctl kubeconfig fails we can't overwrite the kubeconfig file with the error message returned. this commit solves it.
1 parent d373c05 commit e0ac224

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

cmd/helmvm/install.go

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"bytes"
45
"context"
56
"fmt"
67
"io"
@@ -236,24 +237,27 @@ func runK0sctlApply(ctx context.Context) error {
236237
// is overwritten, no questions asked.
237238
func runK0sctlKubeconfig(ctx context.Context) error {
238239
bin := defaults.PathToHelmVMBinary("k0sctl")
239-
kpath := defaults.PathToConfig("kubeconfig")
240-
fp, err := os.OpenFile(kpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
241-
if err != nil {
242-
return fmt.Errorf("unable to open kubeconfig: %w", err)
243-
}
244-
defer fp.Close()
245240
cfgpath := defaults.PathToConfig("k0sctl.yaml")
246241
if _, err := os.Stat(cfgpath); err != nil {
247-
os.RemoveAll(kpath)
248242
return fmt.Errorf("cluster configuration not found")
249243
}
250-
kctl := exec.Command(bin, "kubeconfig", "-c", cfgpath, "--disable-telemetry")
251-
kctl.Stderr = fp
252-
kctl.Stdout = fp
244+
buf := bytes.NewBuffer(nil)
245+
kctl := exec.Command(bin, "kubeconfig", "-c", cfgpath)
246+
kctl.Stderr, kctl.Stdout = buf, buf
253247
if err := kctl.Run(); err != nil {
254-
os.RemoveAll(kpath)
248+
logrus.Errorf("Failed to read kubeconfig:")
249+
logrus.Errorf(buf.String())
255250
return fmt.Errorf("unable to run kubeconfig: %w", err)
256251
}
252+
kpath := defaults.PathToConfig("kubeconfig")
253+
fp, err := os.OpenFile(kpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
254+
if err != nil {
255+
return fmt.Errorf("unable to open kubeconfig: %w", err)
256+
}
257+
defer fp.Close()
258+
if _, err := io.Copy(fp, buf); err != nil {
259+
return fmt.Errorf("unable to write kubeconfig: %w", err)
260+
}
257261
logrus.Infof("Kubeconfig saved to %s", kpath)
258262
return nil
259263
}

0 commit comments

Comments
 (0)