sig.k8s.io/controller-runtime/pkg/client/config/config.go
中的一些定义:
var (
kubeconfig, apiServerURL string
)
func init() {
flag.StringVar(&kubeconfig, "kubeconfig", "",
"Paths to a kubeconfig. Only required if out-of-cluster.")
}
我与 Cobra 的项目“mybinary”:
var rootCmd = &cobra.Command{
Use: "mybinary",
Run: func(cmd *cobra.Command, args []string) {
somefunc()
}
}
func init() {
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file")
rootCmd.InitDefaultHelpFlag()
}
如果我想使用
mybinary --kubeconfig somevalue
来设置kubeconfig
上定义的参数config.go
,我需要做什么?
您有多种选择,但我认为目前您最好的选择可能是使用 cobra 的
PersistentPreRun
功能:
var rootCmd = &cobra.Command{
// ...
PersistentPreRun: func(cmd *cobra.Command, args []string) {
flag.CommandLine.Parse([]string{"-kubeconfig", yourVariableHere})
},
// ...
}
也就是说,在您的根命令或从它派生的任何命令运行之前(前提是它们不覆盖 PreRun),您将调用与调用
flag.Parse()
等效的命令,就像有人运行过一样:
your-program -kubeconfig <string>
其中值来自提供给您自己的 Cobra 标志的参数。如果正确的话,您可以使用
cfgFile
参数,或者添加 --kubeconfig
变量。
如果你使用viper,它似乎有自己的粘合剂可以与基本的
flag
库混合,但我还没有研究过这一点。我确实在 config.go 中看到了这条评论:
// TODO: Fix this to allow double vendoring this library but still register flags on behalf of users
如果修复的话,将提供除调用
flag.CommandLine.Parse
之外的其他方式。