...

Source file src/k8s.io/kubectl/pkg/cmd/create/create_namespace.go

Documentation: k8s.io/kubectl/pkg/cmd/create

     1  /*
     2  Copyright 2015 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package create
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	"github.com/spf13/cobra"
    24  	corev1 "k8s.io/api/core/v1"
    25  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    26  
    27  	"k8s.io/apimachinery/pkg/runtime"
    28  	coreclient "k8s.io/client-go/kubernetes/typed/core/v1"
    29  	"k8s.io/kubectl/pkg/scheme"
    30  	"k8s.io/kubectl/pkg/util"
    31  
    32  	"k8s.io/cli-runtime/pkg/genericclioptions"
    33  	"k8s.io/cli-runtime/pkg/genericiooptions"
    34  	cmdutil "k8s.io/kubectl/pkg/cmd/util"
    35  	"k8s.io/kubectl/pkg/util/i18n"
    36  	"k8s.io/kubectl/pkg/util/templates"
    37  )
    38  
    39  var (
    40  	namespaceLong = templates.LongDesc(i18n.T(`
    41  		Create a namespace with the specified name.`))
    42  
    43  	namespaceExample = templates.Examples(i18n.T(`
    44  	  # Create a new namespace named my-namespace
    45  	  kubectl create namespace my-namespace`))
    46  )
    47  
    48  // NamespaceOptions is the options for 'create namespace' sub command
    49  type NamespaceOptions struct {
    50  	// PrintFlags holds options necessary for obtaining a printer
    51  	PrintFlags *genericclioptions.PrintFlags
    52  	// Name of resource being created
    53  	Name string
    54  
    55  	DryRunStrategy      cmdutil.DryRunStrategy
    56  	ValidationDirective string
    57  	CreateAnnotation    bool
    58  	FieldManager        string
    59  
    60  	Client *coreclient.CoreV1Client
    61  
    62  	PrintObj func(obj runtime.Object) error
    63  
    64  	genericiooptions.IOStreams
    65  }
    66  
    67  // NewNamespaceOptions creates a new *NamespaceOptions with sane defaults
    68  func NewNamespaceOptions(ioStreams genericiooptions.IOStreams) *NamespaceOptions {
    69  	return &NamespaceOptions{
    70  		PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(scheme.Scheme),
    71  		IOStreams:  ioStreams,
    72  	}
    73  }
    74  
    75  // NewCmdCreateNamespace is a macro command to create a new namespace
    76  func NewCmdCreateNamespace(f cmdutil.Factory, ioStreams genericiooptions.IOStreams) *cobra.Command {
    77  
    78  	o := NewNamespaceOptions(ioStreams)
    79  
    80  	cmd := &cobra.Command{
    81  		Use:                   "namespace NAME [--dry-run=server|client|none]",
    82  		DisableFlagsInUseLine: true,
    83  		Aliases:               []string{"ns"},
    84  		Short:                 i18n.T("Create a namespace with the specified name"),
    85  		Long:                  namespaceLong,
    86  		Example:               namespaceExample,
    87  		Run: func(cmd *cobra.Command, args []string) {
    88  			cmdutil.CheckErr(o.Complete(f, cmd, args))
    89  			cmdutil.CheckErr(o.Validate())
    90  			cmdutil.CheckErr(o.Run())
    91  		},
    92  	}
    93  
    94  	o.PrintFlags.AddFlags(cmd)
    95  
    96  	cmdutil.AddApplyAnnotationFlags(cmd)
    97  	cmdutil.AddValidateFlags(cmd)
    98  	cmdutil.AddDryRunFlag(cmd)
    99  	cmdutil.AddFieldManagerFlagVar(cmd, &o.FieldManager, "kubectl-create")
   100  
   101  	return cmd
   102  }
   103  
   104  // Complete completes all the required options
   105  func (o *NamespaceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
   106  	name, err := NameFromCommandArgs(cmd, args)
   107  	if err != nil {
   108  		return err
   109  	}
   110  
   111  	restConfig, err := f.ToRESTConfig()
   112  	if err != nil {
   113  		return err
   114  	}
   115  	o.Client, err = coreclient.NewForConfig(restConfig)
   116  	if err != nil {
   117  		return err
   118  	}
   119  
   120  	o.Name = name
   121  	o.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)
   122  	if err != nil {
   123  		return err
   124  	}
   125  	o.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)
   126  	cmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)
   127  	printer, err := o.PrintFlags.ToPrinter()
   128  	if err != nil {
   129  		return err
   130  	}
   131  	o.PrintObj = func(obj runtime.Object) error {
   132  		return printer.PrintObj(obj, o.Out)
   133  	}
   134  
   135  	o.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)
   136  	return err
   137  }
   138  
   139  // Run calls the CreateSubcommandOptions.Run in NamespaceOpts instance
   140  func (o *NamespaceOptions) Run() error {
   141  	namespace := o.createNamespace()
   142  	if err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, namespace, scheme.DefaultJSONEncoder()); err != nil {
   143  		return err
   144  	}
   145  
   146  	if o.DryRunStrategy != cmdutil.DryRunClient {
   147  		createOptions := metav1.CreateOptions{}
   148  		if o.FieldManager != "" {
   149  			createOptions.FieldManager = o.FieldManager
   150  		}
   151  		createOptions.FieldValidation = o.ValidationDirective
   152  		if o.DryRunStrategy == cmdutil.DryRunServer {
   153  			createOptions.DryRun = []string{metav1.DryRunAll}
   154  		}
   155  		var err error
   156  		namespace, err = o.Client.Namespaces().Create(context.TODO(), namespace, createOptions)
   157  		if err != nil {
   158  			return err
   159  		}
   160  	}
   161  	return o.PrintObj(namespace)
   162  }
   163  
   164  // createNamespace outputs a namespace object using the configured fields
   165  func (o *NamespaceOptions) createNamespace() *corev1.Namespace {
   166  	namespace := &corev1.Namespace{
   167  		TypeMeta:   metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String(), Kind: "Namespace"},
   168  		ObjectMeta: metav1.ObjectMeta{Name: o.Name},
   169  	}
   170  	return namespace
   171  }
   172  
   173  // Validate validates required fields are set to support structured generation
   174  func (o *NamespaceOptions) Validate() error {
   175  	if len(o.Name) == 0 {
   176  		return fmt.Errorf("name must be specified")
   177  	}
   178  	return nil
   179  }
   180  

View as plain text