-
Notifications
You must be signed in to change notification settings - Fork 9
/
kubectl.go
82 lines (66 loc) · 2.32 KB
/
kubectl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package tools
import (
"context"
"fmt"
"os/exec"
"strings"
"github.com/spf13/cobra"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/localexec"
"namespacelabs.dev/foundation/internal/runtime/kubernetes"
"namespacelabs.dev/foundation/internal/sdk/host"
"namespacelabs.dev/foundation/internal/sdk/kubectl"
"namespacelabs.dev/foundation/std/cfg"
)
func NewKubeCtlCmd(hidden bool) *cobra.Command {
cmd := &cobra.Command{
Use: "kubectl -- ...",
Short: "Run kubectl, configured for the specified environment.",
Example: "ns tools kubectl --env=dev get pod -- -A",
Hidden: hidden,
}
keepConfig := cmd.Flags().Bool("keep_config", false, "If set to true, does not delete the generated configuration.")
return fncobra.CmdWithEnv(cmd, func(ctx context.Context, env cfg.Context, args []string) error {
cfg, err := writeKubeconfig(ctx, env, *keepConfig)
if err != nil {
return err
}
defer func() {
_ = cfg.Cleanup()
}()
cmdLine := append(cfg.BaseArgs(), args...)
if *keepConfig {
fmt.Fprintf(console.Stderr(ctx), "Running kubectl %s\n", strings.Join(cmdLine, " "))
}
kubectlBin, err := kubectl.EnsureSDK(ctx, host.HostPlatform())
if err != nil {
return fnerrors.New("failed to download Kubernetes SDK: %w", err)
}
kubectl := exec.CommandContext(ctx, string(kubectlBin), cmdLine...)
return localexec.RunInteractive(ctx, kubectl)
})
}
func writeKubeconfig(ctx context.Context, env cfg.Context, keepConfig bool) (*kubectl.Kubeconfig, error) {
cluster, err := kubernetes.ConnectToNamespace(ctx, env)
if err != nil {
return nil, err
}
kluster := cluster.Cluster().(*kubernetes.Cluster)
k8sconfig := cluster.KubeConfig()
rawConfig, err := kluster.PreparedClient().ClientConfig.RawConfig()
if err != nil {
return nil, fnerrors.New("failed to generate kubeconfig: %w", err)
}
c, err := kubectl.WriteRawKubeconfig(ctx, rawConfig, keepConfig)
if err != nil {
return nil, err
}
c.Namespace = k8sconfig.Namespace
c.Context = k8sconfig.Context
return c, nil
}