K8s client nullptr dereference

33 views Asked by At

Following the k8s/controller-runtime/client example code (see here), which goes a bit like this

var c client.Client

func main() {
    // Using a typed object.
    pod := &corev1.Pod{
        ObjectMeta: metav1.ObjectMeta{
            Namespace: "namespace",
            Name:      "name",
        },
        Spec: corev1.PodSpec{
            Containers: []corev1.Container{
                {
                    Image: "nginx",
                    Name:  "nginx",
                },
            },
        },
    }
    // c is a created client.
    _ = c.Create(context.Background(), pod) // nil deref here  
}

I get a nullptr dereference on _ = c.Create(context.Background(), pod). To me this makes sense, since I declared c, but never initialised it. However the example code also does that. What is going on here?

1

There are 1 answers

0
User12547645 On

The correct way to initialise the client can be found here: https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/client#example-New

cl, err := client.New(config.GetConfigOrDie(), client.Options{})
if err != nil {
    fmt.Println("failed to create client")
    os.Exit(1)
}