Home > other >  How to create a Service Port in Client go
How to create a Service Port in Client go

Time:12-04

I am having trouble adding the Ports field in ServiceSpec. What am I doing wrong?

import (
    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

    port := corev1.ServicePort{}
    port.Port = 8443
    ports := make(corev1.ServicePort, 1)

    service := &corev1.Service{
        ObjectMeta: metav1.ObjectMeta{
            Name:      "test-webhook-admissions",
            Namespace: "test",
            Labels: map[string]string{
                "app.kubernetes.io/instance": "test",
                "app.kubernetes.io/name":     "test",
                "control-plane":              "controller-manager",
            },
        },
        Spec: corev1.ServiceSpec{
            Ports:    ports, // Not working
            Selector: nil,
            //ClusterIP:                "",

        },
    }

CodePudding user response:

Think you have to append the object port to your slice ports.

CodePudding user response:

you are trying to assign the ports variable to the Ports field of the ServiceSpec struct, but you are using the incorrect syntax. To fix the issue, you can use the following code:

port := corev1.ServicePort{}
port.Port = 8443
ports := []corev1.ServicePort{port}

service := &corev1.Service{
    ObjectMeta: metav1.ObjectMeta{
        Name:      "test-webhook-admissions",
        Namespace: "test",
        Labels: map[string]string{
            "app.kubernetes.io/instance": "test",
            "app.kubernetes.io/name":     "test",
            "control-plane":              "controller-manager",
        },
    },
    Spec: corev1.ServiceSpec{
        Ports:    ports,
        Selector: nil,
        //ClusterIP:                "",
    },
}

The main difference is that the ports variable is now defined as a slice of ServicePort objects, instead of a single ServicePort object. Additionally, the Port field of the ServicePort object is set to 8443. You can also add additional ServicePort objects to the ports slice, if necessary.

  • Related