// Namespace implements KubeConfig
func (config DirectClientConfig) Namespace() (string, error) {
	if err := config.ConfirmUsable(); err != nil {
		return "", err
	}

	configContext := config.getContext()

	if len(configContext.Namespace) != 0 {
		return configContext.Namespace, nil
	}

	if len(configContext.NamespacePath) != 0 {
		nsInfo, err := kubectl.LoadNamespaceInfo(configContext.NamespacePath)
		if err != nil {
			return "", err
		}

		return nsInfo.Namespace, nil
	}

	// if nothing was specified, try the default file
	nsInfo, err := kubectl.LoadNamespaceInfo(os.Getenv("HOME") + "/.kubernetes_ns")
	if err != nil {
		return "", err
	}
	return nsInfo.Namespace, nil
}
Example #2
0
func NewCmdNamespace(out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "namespace [<namespace>]",
		Short: "Set and view the current Kubernetes namespace",
		Long: `Set and view the current Kubernetes namespace scope for command line requests.

A Kubernetes namespace subdivides the cluster into groups of logically related pods, services, and replication controllers.

Examples:
  $ kubectl namespace 
  Using namespace default

  $ kubectl namespace other
  Set current namespace to other`,
		Run: func(cmd *cobra.Command, args []string) {
			nsPath := GetFlagString(cmd, "ns-path")
			var err error
			var ns *kubectl.NamespaceInfo
			switch len(args) {
			case 0:
				ns, err = kubectl.LoadNamespaceInfo(nsPath)
				fmt.Printf("Using namespace %s\n", ns.Namespace)
			case 1:
				ns = &kubectl.NamespaceInfo{Namespace: args[0]}
				err = kubectl.SaveNamespaceInfo(nsPath, ns)
				fmt.Printf("Set current namespace to %s\n", ns.Namespace)
			default:
				usageError(cmd, "kubectl namespace [<namespace>]")
			}
			checkErr(err)
		},
	}
	return cmd
}
Example #3
0
func getKubeNamespace(cmd *cobra.Command) string {
	result := api.NamespaceDefault
	if ns := GetFlagString(cmd, "namespace"); len(ns) > 0 {
		result = ns
		glog.V(2).Infof("Using namespace from -ns flag")
	} else {
		nsPath := GetFlagString(cmd, "ns-path")
		nsInfo, err := kubectl.LoadNamespaceInfo(nsPath)
		if err != nil {
			glog.Fatalf("Error loading current namespace: %v", err)
		}
		result = nsInfo.Namespace
	}
	glog.V(2).Infof("Using namespace %s", result)
	return result
}