Last active
December 24, 2021 09:06
-
-
Save able8/df5dfbbfee42dbde85b7b80843f38c33 to your computer and use it in GitHub Desktop.
Use client-go to create/generate/publish an Event object in Kuberentes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"path/filepath" | |
_ "k8s.io/client-go/plugin/pkg/client/auth" | |
"k8s.io/client-go/kubernetes" | |
"k8s.io/client-go/rest" | |
"k8s.io/client-go/tools/clientcmd" | |
"k8s.io/client-go/util/homedir" | |
"k8s.io/klog/v2" | |
v1 "k8s.io/api/core/v1" | |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/client-go/kubernetes/scheme" | |
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" | |
"k8s.io/client-go/tools/record" | |
) | |
func main() { | |
var kubeconfig *string | |
if home := homedir.HomeDir(); home != "" { | |
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") | |
} else { | |
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file") | |
} | |
flag.Parse() | |
// use the current context in kubeconfig | |
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) | |
if err != nil { | |
// use InClusterConfig | |
config, err = rest.InClusterConfig() | |
if err != nil { | |
klog.Fatal(err) | |
} | |
} | |
// creates the clientset | |
clientset, err := kubernetes.NewForConfig(config) | |
if err != nil { | |
klog.Fatal(err) | |
} | |
// create an EventRecorder | |
eventBroadcaster := record.NewBroadcaster() | |
eventBroadcaster.StartLogging(klog.Infof) | |
eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: clientset.CoreV1().Events("")}) | |
eventRecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "By Able"}) | |
// send an Event to default namespace | |
object := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}} | |
eventRecorder.Event(object, v1.EventTypeNormal, "ReasonTest", "MessageTest") | |
// send an Event to kube-public namespace | |
object = &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "kube-public"}} | |
eventRecorder.Event(object, v1.EventTypeNormal, "ReasonTest", "MessageTest") | |
// Wait forever | |
select {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment