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
CodePudding user response:
Using ~
as a shortcut is something specific to bash. ~
just grabs the user's $HOME directory, but does not work across all implementations of the shell. This is something that can be used from the terminal but not always from code (it's not shell-independent). However, go can also find the current user's home directory using os.UserHomeDir()
.
https://pkg.go.dev/os#UserHomeDir
Something like this should work
package main
import (
"fmt"
"os"
)
func main() {
homeDir, _ := os.UserHomeDir()
fmt.Printf("%s/.kube/<kube-config-file>", homeDir)
}
Output: /root/.kube/<kube-config-file>
CodePudding user response:
Since the package you're using mentions that it wraps the Go's os/exec
package, here is an excerpt from their documentation:
Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. The package behaves more like C's "exec" family of functions. To expand glob patterns, either call the shell directly, taking care to escape any dangerous input, or use the path/filepath package's Glob function. To expand environment variables, use package os's ExpandEnv.
So I think you would want to try something like this:
import "os"
getNsCmd := cmd.NewCmd("kubectl", "--kubeconfig", os.ExpandEnv("$HOME/.kube/<kube-config-file>"), "get", "ns")
CodePudding user response:
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")