设置绝对路径在 Go for kubeconfig 中不起作用

Setting absolute path does not work in Go for kubeconfig

我正在使用 Go 模块调用 kubectl,如下所示:

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

如果我这样设置路径就可以了:

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

我正在使用 Go cmd package

目前此模块位于另一个存储库中,这就是它必须向上导航四个级别的原因。我认为这是因为从该文件的角度来看,该命令是 运行ning,但它似乎不应该如此。如果它很简单 运行 将它作为 cli 命令,第一个(我认为)应该可以工作。

当我从 cli 手动 运行 这个命令时它工作得很好:

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

使用 ~ 作为快捷方式是 specific to bash~ 仅获取用户的 $HOME 目录,但不适用于 shell 的所有实现。这是可以从终端使用但不总是从代码使用的东西(它不是 shell-independent)。不过go也可以通过os.UserHomeDir().

找到当前用户的home目录

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)
}

输出:/root/.kube/<kube-config-file>

由于您使用的包提到它包装了 Go 的 os/exec 包,这里摘录自他们的 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.

所以我想你会想尝试这样的事情:

import "os"

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

正如其他人提到的,我需要获取主目录环境变量。 但是我是这样实现的:

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

//

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