其他分享
首页 > 其他分享> > Kubebuilder认证配置文件的加载

Kubebuilder认证配置文件的加载

作者:互联网

kubernetes二次开发-Kubebuilder最佳实践中,我们简单使用了Kubebuilder来资源创建、验证等操作,那么你一定很好奇,程序是如何连接到Kubernetes的,下面我们来简单看下。

来到main.go

	mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
		Scheme:                 scheme,
		MetricsBindAddress:     metricsAddr,
		Port:                   9443,
		HealthProbeBindAddress: probeAddr,
		LeaderElection:         enableLeaderElection,
		LeaderElectionID:       "1de8eaa9.demo.kubebuilder.io",
	})

重点就在“ctrl.GetConfigOrDie()”中,追踪后,最终会来到这个地方:

sigs.k8s.io/controller-runtime/pkg/client/config/config.go


// loadConfig loads a REST Config as per the rules specified in GetConfig.
func loadConfig(context string) (*rest.Config, error) {
	// If a flag is specified with the config location, use that
	if len(kubeconfig) > 0 {
		return loadConfigWithContext("", &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}, context)
	}

	// If the recommended kubeconfig env variable is not specified,
	// try the in-cluster config.
	kubeconfigPath := os.Getenv(clientcmd.RecommendedConfigPathEnvVar)
	if len(kubeconfigPath) == 0 {
		if c, err := loadInClusterConfig(); err == nil {
			return c, nil
		}
	}

	// If the recommended kubeconfig env variable is set, or there
	// is no in-cluster config, try the default recommended locations.
	//
	// NOTE: For default config file locations, upstream only checks
	// $HOME for the user's home directory, but we can also try
	// os/user.HomeDir when $HOME is unset.
	//
	// TODO(jlanford): could this be done upstream?
	loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
	if _, ok := os.LookupEnv("HOME"); !ok {
		u, err := user.Current()
		if err != nil {
			return nil, fmt.Errorf("could not get current user: %v", err)
		}
		loadingRules.Precedence = append(loadingRules.Precedence, filepath.Join(u.HomeDir, clientcmd.RecommendedHomeDir, clientcmd.RecommendedFileName))
	}

	return loadConfigWithContext("", loadingRules, context)
}

该方法完成的功能如下:

标签:err,kubernetes,nil,root,data,Kubebuilder,加载,config,配置文件
来源: https://www.cnblogs.com/cosmos-wong/p/15906367.html