This creates the pkg directory and begins filling it

The majority of the code needs a place to live that's separate from
logic for the commands
This commit is contained in:
Ian Howell 2019-04-25 15:55:10 -05:00
parent ee9e6414bd
commit 58b7abfb79
2 changed files with 44 additions and 31 deletions

@ -1,14 +1,11 @@
package cmd
import (
"flag"
"fmt"
"os"
"path/filepath"
"github.com/spf13/cobra"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
k8s "github.com/ian-howell/airshipadm/pkg/kubernetes"
)
func NewKubernetesVersionCommand() *cobra.Command {
@ -24,25 +21,7 @@ func NewKubernetesVersionCommand() *cobra.Command {
}
func getVersion() string {
var kubeconfig *string
if home := homeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
clientset := k8s.GetClient()
v, err := clientset.Discovery().ServerVersion()
if err != nil {
@ -50,10 +29,3 @@ func getVersion() string {
}
return v.String()
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}

41
pkg/kubernetes/client.go Normal file

@ -0,0 +1,41 @@
package kubernetes
import (
"flag"
"os"
"path/filepath"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
// GetClient creates a kubernetes client using the config at $HOME/.kube/config
func GetClient() *kubernetes.Clientset {
var kubeconfig *string
if home := homeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
return clientset
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}