需求:
创建的service annotaion中如果包含ingress/http: "true"的时候,会自动将该服务的ingress资源创建出来,当删除掉ingress/http: "true"的时候,自动删除ingress, 同时将service删除掉的时候也会自动删除ingress
main.go
Go
package main
import (
"ingress-expose/pkg"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"log"
)
func main() {
//1. config
// 从集群外部创建一个cofnig
config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
if err != nil {
// 从集群内部创建一个config
inClusterConfig, err := rest.InClusterConfig()
if err != nil {
log.Fatalln("can't get config")
}
config = inClusterConfig
}
//2. create client
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalln("can't create clientSet")
}
//3. create informer
factory := informers.NewSharedInformerFactory(clientSet, 0)
serviceInformer := factory.Core().V1().Services()
ingressInformer := factory.Networking().V1().Ingresses()
//4. add event handler
controller := pkg.NewController(clientSet, serviceInformer, ingressInformer)
//5.informer.Start
stopCh := make(chan struct{})
factory.Start(stopCh)
factory.WaitForCacheSync(stopCh)
controller.Run(stopCh)
}
controller.go
Go
package main
import (
"ingress-expose/pkg"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"log"
)
func main() {
//1. config
// 从集群外部创建一个cofnig
config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
if err != nil {
// 从集群内部创建一个config
inClusterConfig, err := rest.InClusterConfig()
if err != nil {
log.Fatalln("can't get config")
}
config = inClusterConfig
}
//2. create client
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalln("can't create clientSet")
}
//3. create informer
factory := informers.NewSharedInformerFactory(clientSet, 0)
serviceInformer := factory.Core().V1().Services()
ingressInformer := factory.Networking().V1().Ingresses()
//4. add event handler
controller := pkg.NewController(clientSet, serviceInformer, ingressInformer)
//5.informer.Start
stopCh := make(chan struct{})
factory.Start(stopCh)
factory.WaitForCacheSync(stopCh)
controller.Run(stopCh)
}