How do I use a MutatingWebhook to inject a container into a Kubernetes pod on creation?

10/23/2019

Using a MutatingWebhook/sidecar injection, I'm trying to add a container to my Kubernetes deployment when it is created. I understand that I have to make a JSON patch, but I'm unclear on the syntax that I need to use to add a container. (I've successfully added labels to the deployment, FWIW.)

I know that JSON patch object looks something like this, but I'm unclear about what to put in the "value" field.

}
  "op":    "add",
  "path":  "/spec/containers",
  "value": "containerName",
}

Here's an example of one of the error messages I get that indicates that something with my syntax is incorrect.

Error creating: Internal error occurred: Internal error occurred: v1.Pod.Spec: v1.PodSpec.Containers: []v1.Container: readObjectStart: expect { or n, but found ", error found in #10 byte of ...|160000}},"{\"name\":|..., bigger context ...|OD","SETGID","SETUID"]},"runAsUser":1000160000}},"{\"name\":\"fluentd\"}"],"dnsPolicy":"ClusterFirst|...
-- bosquito
go
json
kubernetes

1 Answer

10/24/2019

I would've added this as a comment but my rep is too low.

https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/

Shows examples of using kubectl to patch a deployment. The same JSON could be used in your MWH to also patch the deployment.

Kubernetes has extensive go libraries that encapsulate all their Kubernetes objects as go structs. Here is an example of someone injecting a container using a MWH.

https://github.com/morvencao/kube-mutating-webhook-tutorial/blob/master/main.go#L26 <- They load the YAML they will patch from a file (populated by a config map)

https://github.com/morvencao/kube-mutating-webhook-tutorial/blob/master/deployment/configmap.yaml <- Is the YAML content they are injecting(populated by the config map)

https://github.com/morvencao/kube-mutating-webhook-tutorial/blob/master/webhook.go#L132 <- Where they loop over the containers in the deployment and add the container (via a JSON patch)

-- ipushmycar
Source: StackOverflow