// Write out a new kubeconfig
972608
func (b *KubeconfigBuilder) WriteKubecfg() error {
	config, err := b.configAccess.GetStartingConfig()
	if err != nil {
		return fmt.Errorf("error reading kubeconfig: %v", err)
	}

	if config == nil {
		config = &clientcmdapi.Config{}
	}

	{
		cluster := config.Clusters[b.Context]
		if cluster == nil {
			cluster = clientcmdapi.NewCluster()
		}
		cluster.Server = b.Server

		if b.CACert == nil {
			// For now, we assume that the cluster has a "real" cert issued by a CA
			cluster.InsecureSkipTLSVerify = false
			cluster.CertificateAuthority = ""
			cluster.CertificateAuthorityData = nil
		} else {
			cluster.InsecureSkipTLSVerify = false
			cluster.CertificateAuthority = ""
			cluster.CertificateAuthorityData = b.CACert
		}

		if config.Clusters == nil {
			config.Clusters = make(map[string]*clientcmdapi.Cluster)
		}
		config.Clusters[b.Context] = cluster
	}

	{
		authInfo := config.AuthInfos[b.Context]
		if authInfo == nil {
			authInfo = clientcmdapi.NewAuthInfo()
		}

		if b.KubeBearerToken != "" {
			authInfo.Token = b.KubeBearerToken
		} else if b.KubeUser != "" && b.KubePassword != "" {
			authInfo.Username = b.KubeUser
			authInfo.Password = b.KubePassword
		}

		if b.ClientCert != nil && b.ClientKey != nil {
			authInfo.ClientCertificate = ""
			authInfo.ClientCertificateData = b.ClientCert
			authInfo.ClientKey = ""
			authInfo.ClientKeyData = b.ClientKey
		}

		if config.AuthInfos == nil {
			config.AuthInfos = make(map[string]*clientcmdapi.AuthInfo)
		}
		config.AuthInfos[b.Context] = authInfo
	}

	// If we have a bearer token, also create a credential entry with basic auth
	// so that it is easy to discover the basic auth password for your cluster
	// to use in a web browser.
	if b.KubeUser != "" && b.KubePassword != "" {
		name := b.Context + "-basic-auth"
		authInfo := config.AuthInfos[name]
		if authInfo == nil {
			authInfo = clientcmdapi.NewAuthInfo()
		}

		authInfo.Username = b.KubeUser
		authInfo.Password = b.KubePassword

		if config.AuthInfos == nil {
			config.AuthInfos = make(map[string]*clientcmdapi.AuthInfo)
		}
		config.AuthInfos[name] = authInfo
	}

	{
		context := config.Contexts[b.Context]
		if context == nil {
			context = clientcmdapi.NewContext()
		}

		context.Cluster = b.Context
		context.AuthInfo = b.Context

		if b.Namespace != "" {
			context.Namespace = b.Namespace
		}

		if config.Contexts == nil {
			config.Contexts = make(map[string]*clientcmdapi.Context)
		}
		config.Contexts[b.Context] = context
	}

	config.CurrentContext = b.Context

	if err := clientcmd.ModifyConfig(b.configAccess, *config, true); err != nil {
		return err
	}

	fmt.Printf("kops has set your kubectl context to %s\n", b.Context)
	return nil
}
734710
func WriteConfig(filename string, cfg *Config) error {
	b, err := yaml.Marshal(cfg)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(filename, b, 0600)
}
18115
func New(config *Config) (*Kubernetes, error) {
	var err error

	if config == nil {
		config = &Config{}
	}

	if config.ClusterConfig == nil {
		config.ClusterConfig, err = rest.InClusterConfig()
	}

	if err != nil {
		return nil, err
	}

	clientset, err := kubernetes.NewForConfig(config.ClusterConfig)
	if err != nil {
		return nil, err
	}

	return &Kubernetes{Clientset: clientset, Config: config}, nil
}
445262
func (c *NodeupModelContext) BuildKubeConfig(username string, ca, certificate, privateKey []byte) (string, error) {
	user := kubeconfig.KubectlUser{
		ClientCertificateData: certificate,
		ClientKeyData:         privateKey,
	}
	cluster := kubeconfig.KubectlCluster{
		CertificateAuthorityData: ca,
	}

	if c.IsMaster {
		if c.IsKubernetesGTE("1.6") {
			// @note: use https >= 1.6m even for local connections, so we can turn off the insecure port
			cluster.Server = "https://127.0.0.1"
		} else {
			cluster.Server = "http://127.0.0.1:8080"
		}
	} else {
		cluster.Server = "https://" + c.Cluster.Spec.MasterInternalName
	}

	config := &kubeconfig.KubectlConfig{
		ApiVersion: "v1",
		Kind:       "Config",
		Users: []*kubeconfig.KubectlUserWithName{
			{
				Name: username,
				User: user,
			},
		},
		Clusters: []*kubeconfig.KubectlClusterWithName{
			{
				Name:    "local",
				Cluster: cluster,
			},
		},
		Contexts: []*kubeconfig.KubectlContextWithName{
			{
				Name: "service-account-context",
				Context: kubeconfig.KubectlContext{
					Cluster: "local",
					User:    username,
				},
			},
		},
		CurrentContext: "service-account-context",
	}

	yaml, err := kops.ToRawYaml(config)
	if err != nil {
		return "", fmt.Errorf("error marshaling kubeconfig to yaml: %v", err)
	}

	return string(yaml), nil
}
184181
func CreateKubeConfigFromCluster(c *container.Cluster) (*KubeConfig, error) {
	contextName := strings.ToLower(c.Name)
	authInfoName := contextName

	var clusters []NamedCluster
	cluster := Cluster{
		Server: fmt.Sprintf("https://%s", c.Endpoint),
		CertificateAuthorityData: c.MasterAuth.ClusterCaCertificate,
	}
	namedCluster := NamedCluster{
		Name:    c.Name,
		Cluster: cluster,
	}
	clusters = append(clusters, namedCluster)

	var contexts []NamedContext
	context := Context{
		Cluster:  c.Name,
		AuthInfo: authInfoName,
	}
	namedContext := NamedContext{
		Name:    contextName,
		Context: context,
	}
	contexts = append(contexts, namedContext)

	var authInfos []NamedAuthInfo
	authInfo := AuthInfo{
		ClientCertificateData: c.MasterAuth.ClientCertificate,
		ClientKeyData:         c.MasterAuth.ClientKey,
		Username:              c.MasterAuth.Username,
		Password:              c.MasterAuth.Password,
	}
	namedAuthInfo := NamedAuthInfo{
		Name:     authInfoName,
		AuthInfo: authInfo,
	}
	authInfos = append(authInfos, namedAuthInfo)

	return &KubeConfig{
		CurrentContext: contextName,
		APIVersion:     kubeconfigAPIVersion,
		Clusters:       clusters,
		Contexts:       contexts,
		AuthInfos:      authInfos,
	}, nil
}
61110
func NewPodConfig(mode PodConfigNotificationMode, recorder record.EventRecorder) *PodConfig {
	updates := make(chan kubetypes.PodUpdate, 50)
	storage := newPodStorage(updates, mode, recorder)
	podConfig := &PodConfig{
		pods:    storage,
		mux:     config.NewMux(storage),
		updates: updates,
		sources: sets.String{},
	}
	return podConfig
}
911027
func runUploadKubeadmConfig(c workflow.RunData) error {
	cfg, client, err := getUploadConfigData(c)
	if err != nil {
		return err
	}

	klog.V(1).Infoln("[upload-config] Uploading the kubeadm ClusterConfiguration to a ConfigMap")
	if err := uploadconfig.UploadConfiguration(cfg, client); err != nil {
		return errors.Wrap(err, "error uploading the kubeadm ClusterConfiguration")
	}
	return nil
}
169738
func NewCloudConfig(contents string) (*CloudConfig, error) {
	yaml.UnmarshalMappingKeyTransform = func(nameIn string) (nameOut string) {
		return strings.Replace(nameIn, "-", "_", -1)
	}
	var cfg CloudConfig
	err := yaml.Unmarshal([]byte(contents), &cfg)
	return &cfg, err
}
264265
func FetchKubeConfig(server string) (*k8s.KubeConfig, error) {
	f, err := ioutil.TempFile("", "kubeconfig")
	if err != nil {
		log.Printf("Error while trying to create temp file for kubeconfig:%s\n", err)
		return nil, err
	}
	conn := fmt.Sprintf("azureuser@%s:.kube/config", server)
	cmd := exec.Command("scp", "-oStrictHostKeyChecking=no", conn, f.Name())
	err = cmd.Start()
	if err != nil {
		log.Printf("Error while trying to start SCP:%s\n", err)
		return nil, err
	}
	err = cmd.Wait()
	if err != nil {
		log.Printf("Error while waiting for SCP to complete:%s\n", err)
		return nil, err
	}

	contentInBytes, err := ioutil.ReadFile(f.Name())
	kubeConfig, err := k8s.CreateKubeConfig(contentInBytes)
	if err != nil {
		return nil, err
	}
	return kubeConfig, nil
}
853603
func NewKubeletConfig(k8s config.KubernetesConfig, r cruntime.Manager) (string, error) {
	version, err := ParseKubernetesVersion(k8s.KubernetesVersion)
	if err != nil {
		return "", errors.Wrap(err, "parsing kubernetes version")
	}

	extraOpts, err := ExtraConfigForComponent(Kubelet, k8s.ExtraOptions, version)
	if err != nil {
		return "", errors.Wrap(err, "generating extra configuration for kubelet")
	}

	for k, v := range r.KubeletOptions() {
		extraOpts[k] = v
	}
	if k8s.NetworkPlugin != "" {
		extraOpts["network-plugin"] = k8s.NetworkPlugin
	}

	podInfraContainerImage, _ := constants.GetKubeadmCachedImages(k8s.ImageRepository, k8s.KubernetesVersion)
	if _, ok := extraOpts["pod-infra-container-image"]; !ok && k8s.ImageRepository != "" && podInfraContainerImage != "" {
		extraOpts["pod-infra-container-image"] = podInfraContainerImage
	}

	// parses a map of the feature gates for kubelet
	_, kubeletFeatureArgs, err := ParseFeatureArgs(k8s.FeatureGates)
	if err != nil {
		return "", errors.Wrap(err, "parses feature gate config for kubelet")
	}

	if kubeletFeatureArgs != "" {
		extraOpts["feature-gates"] = kubeletFeatureArgs
	}

	extraFlags := convertToFlags(extraOpts)

	b := bytes.Buffer{}
	opts := struct {
		ExtraOptions     string
		ContainerRuntime string
	}{
		ExtraOptions:     extraFlags,
		ContainerRuntime: k8s.ContainerRuntime,
	}
	if err := kubeletSystemdTemplate.Execute(&b, opts); err != nil {
		return "", err
	}

	return b.String(), nil
}
447874
func newCmdKubeConfigUtility(out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "kubeconfig",
		Short: "Kubeconfig file utilities",
		Long:  kubeconfigLongDesc,
	}

	cmd.AddCommand(newCmdUserKubeConfig(out))
	return cmd
}
79564
func WriteConfigFile(fileName string, cfg *kubeschedulerconfig.KubeSchedulerConfiguration) error {
	const mediaType = runtime.ContentTypeYAML
	info, ok := runtime.SerializerInfoForMediaType(kubeschedulerscheme.Codecs.SupportedMediaTypes(), mediaType)
	if !ok {
		return fmt.Errorf("unable to locate encoder -- %q is not a supported media type", mediaType)
	}

	encoder := kubeschedulerscheme.Codecs.EncoderForVersion(info.Serializer, kubeschedulerconfigv1alpha1.SchemeGroupVersion)

	configFile, err := os.Create(fileName)
	if err != nil {
		return err
	}
	defer configFile.Close()
	if err := encoder.Encode(cfg, configFile); err != nil {
		return err
	}

	return nil
}
928374
func (p *Process) writeConfig() error {
	logger := p.Logger.New("fn", "writeConfig")
	logger.Info("writing")

	// Create parent directory if it doesn't exist.
	if err := os.MkdirAll(filepath.Dir(p.ConfigPath()), 0777); err != nil {
		logger.Error("cannot create config parent directory", "err", err)
		return err
	}

	f, err := os.Create(p.ConfigPath())
	if err != nil {
		logger.Error("cannot create config file", "err", err)
		return err
	}
	defer f.Close()

	return configTemplate.Execute(f, struct {
		ID       string
		Port     string
		DataDir  string
		Password string
	}{p.ID, p.Port, p.DataDir, p.Password})
}
1357587
func WriteKubeConfigWithClientCert(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName string, organizations []string) error {

	// creates the KubeConfigSpecs, actualized for the current InitConfiguration
	caCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
	if err != nil {
		return errors.Wrap(err, "couldn't create a kubeconfig; the CA files couldn't be loaded")
	}

	controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
	if err != nil {
		return err
	}

	spec := &kubeConfigSpec{
		ClientName: clientName,
		APIServer:  controlPlaneEndpoint,
		CACert:     caCert,
		ClientCertAuth: &clientCertAuth{
			CAKey:         caKey,
			Organizations: organizations,
		},
	}

	return writeKubeConfigFromSpec(out, spec, cfg.ClusterName)
}
942141
func Write(config clientcmdapi.Config) ([]byte, error) {
	return runtime.Encode(clientcmdlatest.Codec, &config)
}
524969
func WriteKubeletDynamicEnvFile(cfg *kubeadmapi.ClusterConfiguration, nodeReg *kubeadmapi.NodeRegistrationOptions, registerTaintsUsingFlags bool, kubeletDir string) error {
	hostName, err := nodeutil.GetHostname("")
	if err != nil {
		return err
	}

	flagOpts := kubeletFlagsOpts{
		nodeRegOpts:              nodeReg,
		featureGates:             cfg.FeatureGates,
		pauseImage:               images.GetPauseImage(cfg),
		registerTaintsUsingFlags: registerTaintsUsingFlags,
		execer:                   utilsexec.New(),
		pidOfFunc:                procfs.PidOf,
		defaultHostname:          hostName,
	}
	stringMap := buildKubeletArgMap(flagOpts)
	argList := kubeadmutil.BuildArgumentListFromMap(stringMap, nodeReg.KubeletExtraArgs)
	envFileContent := fmt.Sprintf("%s=%q\n", constants.KubeletEnvFileVariableName, strings.Join(argList, " "))

	return writeKubeletFlagBytesToDisk([]byte(envFileContent), kubeletDir)
}
867628
func (c *installationSiteConfig) write(path string) error {
	blob, err := json.MarshalIndent(c, "", "\t")
	if err != nil {
		return err
	}
	return ioutil.WriteFile(path, blob, 0666)
}