kubernetes / client-go

Go client for Kubernetes.
Apache License 2.0
8.99k stars 2.94k forks source link

build istio gateway by using dynamic go client #1307

Closed gandalf-the-white closed 11 months ago

gandalf-the-white commented 11 months ago

I used unstructured.Unstructured for every thing until my istio gateway. I used "kubectl api-resources | grep gateway" to obtains information relatives to the schema, kubectl api-resources | grep gateway gateways gw networking.istio.io/v1beta1 true Gateway

but at the end, I have this error Failed to create gateway: the server could not find the requested resource

Can someone help me?

Here is my function,

func (c *K8sDynamicClient) CreateGateway(name, namespace string, ingress string, host string) { gatewayRes := schema.GroupVersionResource{ Group: "networking.istio.io", Version: "v1beta1", Resource: "gateways", }

    gatewayObject := &unstructured.Unstructured{
            Object: map[string]interface{}{
                    "apiVersion": "networking.istio.io/v1beta1",
                    "kind":       "Gateway",
                    "metadata": map[string]interface{}{
                            "name":      name,
                            "namespace": namespace,
                    },
                    "spec": map[string]interface{}{
                            "selector": map[string]interface{}{
                                    "istio": ingress,
                            },
                            "server": []map[string]interface{}{
                                    {
                                            "hosts": []string{
                                                    host,
                                            },
                                            "ports": map[string]interface{}{
                                                    "name":     "http",
                                                    "number":   80,
                                                    "protocol": "HTTP",
                                            },
                                    },
                            },
                    },
            },
    }

    gateway, err := c.Client.Resource(gatewayRes).Create(context.TODO(), gatewayObject, metav1.CreateOptions{})
    if err != nil {
            log.Fatalf("Failed to create gateway: %v\n", err)
    }

}

liggitt commented 11 months ago

Gateways are a namespaced resource, your client needs to set Namespace(namespace) to make it submit the request to a namespaced endpoint

gandalf-the-white commented 11 months ago

Thx a lot Jordan, you unlocked my problem.