Setting absolute path does not work in Go for kubeconfig

Issue

I am making a call to kubectl from with a Go module like so:

getNsCmd := cmd.NewCmd("kubectl", "--kubeconfig", "~/.kube/<kube-config-file>", "get", "ns")

It works if I set the path like this:

getNsCmd := cmd.NewCmd("kubectl", "--kubeconfig", "../../../../.kube/<kube-config-file>", "get", "ns")

I am using the Go cmd package

Currently this module lives in another repo and that’s why it has to navigate up four levels. I figure this is because the command is running from the perspective of this file, but it doesn’t seem like it should have to. If it’s simple running it as a cli command the first one (I would think) should work.

When I run this command from the cli manually it works just fine:

$ kubectl --kubeconfig ~/.kube/<kube-config-file> get ns

Solution

As others have mentioned I needed to grab the home directory environment var.
However I implemented it like this:

    homePath, _ := os.LookupEnv("HOME")

//

getNsCmd := cmd.NewCmd("kubectl", "--kubeconfig", homePath+"/.kube/<kube-config-file>", "get", "ns")

Answered By – NayefMusa

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.