/
main.go
91 lines (77 loc) · 2.35 KB
/
main.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
83
84
85
86
87
88
89
90
91
package main
import (
"context"
"flag"
"fmt"
"os"
"path/filepath"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
type flagOptions struct {
kubeconfig *string
namespace *string
n *string
o *string
output *string
}
const (
defaultOutput = "wide"
jsonOutput = "json"
outputUsage = "output format"
namespaceUsage = "namespace to search for secret(s)"
kubeconfigUsage = "path to search for kubeconfig file"
)
var flags flagOptions
func init() {
flags.namespace = flag.String("namespace", apiv1.NamespaceDefault, namespaceUsage)
flags.n = flag.String("n", apiv1.NamespaceDefault, namespaceUsage+" (shorthand)")
flags.kubeconfig = flag.String("kubeconfig", getKubeConfig(), kubeconfigUsage)
flags.output = flag.String("output", defaultOutput, outputUsage)
flags.o = flag.String("o", defaultOutput, outputUsage+" (shorthand)")
}
func main() {
flag.Parse()
config, err := clientcmd.BuildConfigFromFlags("", *flags.kubeconfig)
if err != nil {
fmt.Fprintf(os.Stdout, "Could not create client from kubeconfig: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Fprintf(os.Stdout, "Could not create clientset from config: %v", err)
}
list, err := getSecrets(clientset, *flags.namespace)
if err != nil {
fmt.Fprintf(os.Stdout, "Could not get secrets: %v", err)
}
// print output based on -o or --output flag
switch {
case *flags.o == jsonOutput:
jsonPrintSecrets(list.Items)
default:
widePrintSecrets(list.Items)
}
}
// getSecrets creates the secrets clients from corev1 api
// and returns all secrets in the designated namespace
func getSecrets(c kubernetes.Interface, namespace string) (*apiv1.SecretList, error) {
secretsClient := c.CoreV1().Secrets(namespace)
list, err := secretsClient.List(context.TODO(), metav1.ListOptions{})
if err != nil {
return &apiv1.SecretList{}, fmt.Errorf("could not list secrets: %v", err)
}
return list, nil
}
// getKubeConfig passes back the user's kubeconfig file path
// first precendence is KUBECONFIG env var
// if not set, return $HOME/.kube/config
func getKubeConfig() string {
kCfgPath := os.Getenv("KUBECONFIG")
if kCfgPath != "" {
return kCfgPath
}
return filepath.Join(homedir.HomeDir(), ".kube", "config")
}