kubernetessecurity-context

kubernetes: using value of runAsUser in an environment variable using valueFrom?


I have a kubernetes deployment that starts a pod that includes a runAsUser key in its securityContext. I was hoping I could stick this value in the environment of an initContainer using valueFrom, like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: testdeployment
spec:
  template:
    spec:
      containers:
        - name: myservice
          image: myimage
          securityContext:
            runAsUser: 1000
      initContainers:
        - name: initialize_things
          image: myimage
          env:
            - name: CONTAINER_UID
              valueFrom:
                fieldRef:
                  fieldPath: spec.containers[0].securityContext.runAsUser

That doesn't seem to work:

The Deployment "testdeployment" is invalid: spec.template.spec.initContainers[0].env[0].valueFrom.fieldRef.fieldPath: Invalid value: "spec.containers[0].securityContext.runAsUser": error converting fieldPath: field label not supported: spec.containers[0].securityContext.runAsUser

Is there any way to make this work? I'm trying to reduce the number of places I'm hardcoding that UID.


Solution

  • I think you cant make this work because The downward API doesnt support spec.containers[0].securityContext.runAsUser as a field.

    Btw, in your case more logically was to put full path , I mean spec.template.spec.containers[0].securityContext.runAsUser, but anyway, it wont help

    As per Capabilities of the Downward API - you are able to use only few fields

    Information available via fieldRef:
    metadata.name 
    metadata.namespace
    metadata.uid 
    metadata.labels['<KEY>']
    metadata.annotations['<KEY>'] 
    
    In addition, the following information is available through downwardAPI volume fieldRef:    
    metadata.labels
    metadata.annotations 
    
    The following information is available through environment variables:    
    status.podIP 
    spec.serviceAccountName 
    spec.nodeName 
    status.hostIP
    

    You can find very similar issue on github closed: how to get imageID in container