可以从Golang代码中运行`kubectl get events`吗?

huangapple go评论91阅读模式
英文:

Is it possible to run 'kubectl get events' from golang code

问题

我想获取 Kubernetes 事件列表并将其存储,我该如何在 Golang 代码中运行 'kubectl get events' 命令?

我尝试了下面的代码,但是出现了 "exec: 'kubectl get events': 在 $PATH 中找不到可执行文件" 的错误提示。

package main
  
import (
    "fmt"
    "os/exec"
)

func main() {
    out, err := exec.Command("kubectl", "get", "events").Output()
    if err != nil {
        fmt.Printf("%s", err)
    }
    fmt.Println("Command Successfully Executed")
    output := string(out[:])
    fmt.Println(output)
}

你可以尝试使用 exec.Command 函数,并将命令和参数作为参数传递给它。在这种情况下,你可以将 "kubectl" 作为命令,"get" 和 "events" 作为参数传递给 exec.Command 函数。然后,你可以使用 Output 方法来执行命令并获取输出结果。

英文:

I want to get the list of kubernetes events and store it, how can I run 'kubectl get events' from a golang code.

I tried the below but getting "exec: "kubectl get events": executable file not found in $PATHCommand Successfully Executed"

package main
  
import (
    "fmt"
    "os/exec"
//    "runtime"
)

func main() {
    out, err := exec.Command("kubectl get events").Output()
    if err != nil {
        fmt.Printf("%s", err)
    }
    fmt.Println("Command Successfully Executed")
    output := string(out[:])
    fmt.Println(output)
}

答案1

得分: 1

首先,我会听从@zerkms的建议,并使用go-client查询任何k8s信息-这样做将更容易提取数据,而不是处理混乱的命令行输出解析/错误检查。


如果你必须exec到外部程序,请确保正确使用exec.Command,将可执行文件及其各个参数作为可变参数列出:

out, err := exec.Command("kubectl", "get", "events").Output()

调用:

exec.Command("kubectl get events")

会失败,因为它尝试在你的路径中找到一个名为kubectl get events的单个可执行文件,而不是预期的kubectl命令。

英文:

Firstly, I would heed @zerkms 's advice and query any k8s info with the go-client - doing so will make it much easier to extract data rather than dealing with messy command-line output parsing/error-checking.


If you must exec to an external program, ensure you use exec.Command correctly, listing the executable and its individual arguments as variadic arguments:

out, err := exec.Command("kubectl", "get", "events").Output()

calling:

exec.Command("kubectl get events")

fails, as it tries to find a single executable file in your path called kubectl get events instead of the intended kubectl command.

huangapple
  • 本文由 发表于 2022年11月30日 08:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/74621678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定