Skip to content

Commit

Permalink
Merge pull request kubernetes#101769 from eddiezane/automated-cherry-…
Browse files Browse the repository at this point in the history
…pick-of-#101005-upstream-release-1.20

Automated cherry pick of kubernetes#101005: Set namespace when using kubectl create service
  • Loading branch information
k8s-ci-robot authored May 7, 2021
2 parents 097a895 + 61e6599 commit c28b41d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
15 changes: 11 additions & 4 deletions staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ type ServiceOptions struct {
FieldManager string
CreateAnnotation bool
Namespace string
EnforceNamespace bool

Client corev1client.CoreV1Interface
DryRunStrategy cmdutil.DryRunStrategy
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -177,13 +178,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,
Expand Down
22 changes: 22 additions & 0 deletions staging/src/k8s.io/kubectl/pkg/cmd/create/create_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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())
}
}

0 comments on commit c28b41d

Please sign in to comment.