How to use the watch in api.ListOptions with client-go the client SDK of kubernetes

1/9/2017

I want to watch the change of namespaces in kubernetes cluster, with code like:

... log.Infoln("====== 1 ======= ") namespaces, err := clientset.Namespaces().List(api.ListOptions{Watch: true}) if err != nil { log.Errorln("Get namespaces from kubernetes cluster error:%v", err) } log.Infoln("====== 2 ======= ") for _, namespace := range namespaces.Items { log.Println("=======>> namespaces: ", namespace) } ...

this code will block at namespaces, err := clientset.Namespaces().List(api.ListOptions{Watch: true}). But there is no response when I create new namespace either delete the namespaces.

the client-go is k8s.io/client-go/1.5/

Anyone can give me the example code for this, thanks.

-- sope
kubernetes

1 Answer

1/10/2017

I had foud the answer:

var watch watch.Interface
if watch, err = clientset.Namespaces().Watch(api.ListOptions{Watch: true}); err != nil {
    log.Errorln("Watch namespaces from kubernetes cluster error:%v", err)
    return
}

eventChan := watch.ResultChan()
for event := range eventChan {
    log.Infoln(event)
}
-- sope
Source: StackOverflow