Getting git to work in a kubernetes container when using runAsUser

473 views Asked by At

I'd like to run git as part of an initContainer in a Kubernetes pod. I'd also like the containers to run as an arbitrary non-root user. Is there any way to make this happen?

The problem is that if I include something like this in the pod description:

securityContext:
  runAsUser: 1234

Then git will fail like this:

No user exists for uid 1234
fatal: Could not read from remote repository.

The error comes from ssh. The obvious workaround is to clone via an https:// url rather than using ssh, but I'm relying on a deploy key for read-only access to the remote repository.

I can't bake the user into the image because I don't know what the user id will be until runtime.

I can't add the user to /etc/passwd at runtime because the container is running as a non-root user.

How are other folks handling this sort of situation?

In case someone asks:

$ kubectl version
Server Version: version.Info{Major:"1", Minor:"18", GitVersion:"v1.18.9+k3s1", GitCommit:"630bebf94b9dce6b8cd3d402644ed023b3af8f90", GitTreeState:"clean", BuildDate:"2020-09-17T19:05:07Z", GoVersion:"go1.13.15", Compiler:"gc", Platform:"linux/amd64"}
1

There are 1 answers

0
shawnzhu On

You can use securityContext at container level instead of pod level.

apiVersion: v1
kind: Pod
metadata:
  name: security-context-demo
spec:
  securityContext:
    runAsUser: 1000
  initContainers:
  - name: sec-ctx-in-init
    image: busybox
    securityContext:
      runAsUser: 2000
    command: ['sh', '-c', 'id']
  containers:
  - name: sec-ctx-in-container
    image: gcr.io/google-samples/node-hello:1.0
    securityContext:
      runAsUser: 3000
      allowPrivilegeEscalation: false

After creating the pod (I use katacoda), you can run:

master $ kubectl logs security-context-demo -c sec-ctx-in-init
uid=2000 gid=0(root)
master $ kubectl exec -it security-context-demo -c sec-ctx-in-container -- id
uid=3000 gid=0(root) groups=0(root)

Notice: if you are actually sharing files between container and initcontainer, you need to specify the same fsGroup at pod level securitycontext.