Merge pull request #101005 from zxh326/fix-create-service

Set namespace when using kubectl create service
This commit is contained in:
Kubernetes Prow Robot 2021-04-29 09:00:51 -07:00 committed by GitHub
commit 02c556d4d2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 4 deletions

View File

@ -72,6 +72,7 @@ type ServiceOptions struct {
FieldManager string
CreateAnnotation bool
Namespace string
EnforceNamespace bool
Client corev1client.CoreV1Interface
DryRunStrategy cmdutil.DryRunStrategy
@ -105,7 +106,7 @@ func (o *ServiceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []
return err
}
o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
@ -173,13 +174,19 @@ func (o *ServiceOptions) createService() (*corev1.Service, error) {
selector := map[string]string{}
selector["app"] = o.Name
namespace := ""
if o.EnforceNamespace {
namespace = o.Namespace
}
service := corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: o.Name,
Labels: labels,
Name: o.Name,
Labels: labels,
Namespace: namespace,
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceType(o.Type),
Type: o.Type,
Selector: selector,
Ports: ports,
ExternalName: o.ExternalName,

View File

@ -17,6 +17,9 @@ limitations under the License.
package create
import (
"k8s.io/cli-runtime/pkg/genericclioptions"
restclient "k8s.io/client-go/rest"
cmdtesting "k8s.io/kubectl/pkg/cmd/testing"
"testing"
v1 "k8s.io/api/core/v1"
@ -267,3 +270,22 @@ func TestCreateServices(t *testing.T) {
})
}
}
func TestCreateServiceWithNamespace(t *testing.T) {
svcName := "test-service"
ns := "test"
tf := cmdtesting.NewTestFactory().WithNamespace(ns)
defer tf.Cleanup()
tf.ClientConfigVal = &restclient.Config{}
ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
cmd := NewCmdCreateServiceClusterIP(tf, ioStreams)
cmd.Flags().Set("dry-run", "client")
cmd.Flags().Set("output", "jsonpath={.metadata.namespace}")
cmd.Flags().Set("clusterip", "None")
cmd.Run(cmd, []string{svcName})
if buf.String() != ns {
t.Errorf("expected output: %s, but got: %s", ns, buf.String())
}
}