<p>I'd like to run <code>git</code> as part of an <code>initContainer</code> 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?</p>
<p>The problem is that if I include something like this in the pod description:</p>
<pre><code>securityContext:
  runAsUser: 1234
</code></pre>
<p>Then <code>git</code> will fail like this:</p>
<pre><code>No user exists for uid 1234
fatal: Could not read from remote repository.
</code></pre>
<p>The error comes from <code>ssh</code>. The obvious workaround is to clone via an <code>https://</code> url rather than using <code>ssh</code>, but I'm relying on a deploy key for read-only access to the remote repository.</p>
<p>I can't bake the user into the image because I don't know what the user id will be until runtime.</p>
<p>I can't add the user to <code>/etc/passwd</code> at runtime because the container is running as a non-root user.</p>
<p>How are other folks handling this sort of situation?</p>
<p>In case someone asks:</p>
<pre><code>$ kubectl version
Server Version: version.Info{Major:&quot;1&quot;, Minor:&quot;18&quot;, GitVersion:&quot;v1.18.9+k3s1&quot;, GitCommit:&quot;630bebf94b9dce6b8cd3d402644ed023b3af8f90&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2020-09-17T19:05:07Z&quot;, GoVersion:&quot;go1.13.15&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;}
</code></pre>

larsks
<p>You can use securityContext at container level instead of pod level.</p>
<pre class="lang-yaml prettyprint-override"><code>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
</code></pre>
<p>After creating the pod (I use katacoda), you can run:</p>
<pre class="lang-bash prettyprint-override"><code>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)
</code></pre>
<p><strong>Notice</strong>: if you are actually sharing files between container and initcontainer, you need to specify the same <code>fsGroup</code> at pod level securitycontext.</p>
