这是使用 istio client-go创建 istio 虚拟服务的示例。在这里,我们使用istio.io/api/networking/v1alpha3
andistio.io/client-go/pkg/apis/networking/v1alpha3
来创建VirtualService
自定义资源规范。之后使用istio.io/client-go/pkg/clientset/versioned
实际将此规范发送到 kubernetes API 服务器。
package main
import (
"context"
"log"
"os"
v1alpha3Spec "istio.io/api/networking/v1alpha3"
"istio.io/client-go/pkg/apis/networking/v1alpha3"
versionedclient "istio.io/client-go/pkg/clientset/versioned"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
kubeconfig := os.Getenv("KUBECONFIG")
namespace := os.Getenv("NAMESPACE")
if len(kubeconfig) == 0 || len(namespace) == 0 {
log.Fatalf("Environment variables KUBECONFIG and NAMESPACE need to be set")
}
restConfig, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatalf("Failed to create k8s rest client: %s", err)
}
ic, err := versionedclient.NewForConfig(restConfig)
if err != nil {
log.Fatalf("Failed to create istio client: %s", err)
}
var host []string
host[0] = "abc.com"
virtualServiceCrd := &v1alpha3.VirtualService{
TypeMeta: metav1.TypeMeta{
APIVersion: "networking.istio.io/v1alpha3",
Kind: "Virtualservice",
},
ObjectMeta: metav1.ObjectMeta{
Name: "default",
},
Spec: v1alpha3Spec.VirtualService{
Hosts: host,
},
}
ic.NetworkingV1alpha3().VirtualServices(namespace).Create(context.TODO(), virtualServiceCrd, metav1.CreateOptions{})
}