<p>I am working on Opersator-SDK. In my operator controller, I try to create an Istio Custom resource -- virtualservices. The definition of virtualservices looks like as following:</p>
<pre><code>kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
  name: virtualservices.networking.istio.io
</code></pre>
<p>Here I think there are a few of things that have to do first:</p>
<ol>
<li>Get Istio API module</li>
<li>In my controller code, import istio virtualservices package</li>
<li>How to create/update virtualservice resource</li>
</ol>
<p>My question is how to do them? Because I never do that before, so have to ask for help how to do that.</p>

<p>Here is an example of creating a istio virtual service using istio <a href="https://github.com/istio/client-go" rel="nofollow noreferrer">client-go</a>. Here we are using <code>istio.io/api/networking/v1alpha3</code> and <code>istio.io/client-go/pkg/apis/networking/v1alpha3</code> to create the <code>VirtualService</code> custom resource spec. After that using <code>istio.io/client-go/pkg/clientset/versioned</code> to actually sending this spec to kubernetes API server.</p>
<pre><code>package main

import (
    &quot;context&quot;
    &quot;log&quot;
    &quot;os&quot;

    v1alpha3Spec &quot;istio.io/api/networking/v1alpha3&quot;
    &quot;istio.io/client-go/pkg/apis/networking/v1alpha3&quot;
    versionedclient &quot;istio.io/client-go/pkg/clientset/versioned&quot;
    metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;
    &quot;k8s.io/client-go/tools/clientcmd&quot;
)

func main() {

    kubeconfig := os.Getenv(&quot;KUBECONFIG&quot;)
    namespace := os.Getenv(&quot;NAMESPACE&quot;)

    if len(kubeconfig) == 0 || len(namespace) == 0 {
        log.Fatalf(&quot;Environment variables KUBECONFIG and NAMESPACE need to be set&quot;)
    }

    restConfig, err := clientcmd.BuildConfigFromFlags(&quot;&quot;, kubeconfig)
    if err != nil {
        log.Fatalf(&quot;Failed to create k8s rest client: %s&quot;, err)
    }

    ic, err := versionedclient.NewForConfig(restConfig)
    if err != nil {
        log.Fatalf(&quot;Failed to create istio client: %s&quot;, err)
    }
    var host []string
    host[0] = &quot;abc.com&quot;
    virtualServiceCrd := &amp;v1alpha3.VirtualService{
        TypeMeta: metav1.TypeMeta{
            APIVersion: &quot;networking.istio.io/v1alpha3&quot;,
            Kind:       &quot;Virtualservice&quot;,
        },
        ObjectMeta: metav1.ObjectMeta{
            Name: &quot;default&quot;,
        },
        Spec: v1alpha3Spec.VirtualService{
            Hosts: host,
        },
    }

    ic.NetworkingV1alpha3().VirtualServices(namespace).Create(context.TODO(), virtualServiceCrd, metav1.CreateOptions{})
}
</code></pre>
