Get the Kubernetes uid of the Deployment that created the pod, from within the pod

11/3/2021

I want to be able to know the Kubernetes uid of the Deployment that created the pod, from within the pod.

The reason for this is so that the Pod can spawn another Deployment and set the OwnerReference of that Deployment to the original Deployment (so it gets Garbage Collected when the original Deployment is deleted).

Taking inspiration from here, I've tried*:

1) Using field refs as env vars:

containers:
  - name: test-operator
    env:
      - name: DEPLOYMENT_UID
        valueFrom: 
          fieldRef: {fieldPath: metadata.uid}

2) Using downwardAPI and exposing through files on a volume:

containers:
  volumeMounts:
    - mountPath: /etc/deployment-info
      name: deployment-info
volumes:
  - name: deployment-info
    downwardAPI:
      items:
      - path: "uid"
        fieldRef: {fieldPath: metadata.uid}

*Both of these are under spec.template.spec of a resource of kind: Deployment.

However for both of these the uid is that of the Pod, not the Deployment. Is what I'm trying to do possible?

-- James Cockbain
kubernetes
kubernetes-pod

2 Answers

11/4/2021

The behavior is correct, the Downward API is for pod rather than deployment/replicaset.

So I guess the solution is set the name of deployment manually in spec.template.metadata.labels, then adopt Downward API to inject the labels as env variables.

-- vincent pli
Source: StackOverflow

11/29/2021

I think it's impossible to get the UID of Deployment itself, you can set any range of runAsUser while creating the deployment.

Try this command to get the UIDs of the existing pods:

kubectl get pod -o jsonpath='{range .items[*]}{@.metadata.name}{" runAsUser: "}{@.spec.containers[*].securityContext.runAsUser}{" fsGroup: "}{@.spec.securityContext.fsGroup}{" seLinuxOptions: "}{@.spec.securityContext.seLinuxOptions.level}{"\n"}{end}'

It's not the exact what you wanted to get, but it can be a hint for you.

To set the UID while creating the Deployment, see the example below:

apiVersion: apps/v1
kind: Deployment
metadata:
 name: toolbox2
 labels:
   app: toolbox2
spec:
 replicas: 3
 selector:
   matchLabels:
     app: toolbox2
 template:
   metadata:
     labels:
       app: toolbox2
   spec:
     securityContext:
       supplementalGroups: [1000620001]
       seLinuxOptions:
           level: s0:c25,c10
     containers:
     - name: net-toolbox
       image: quay.io/wcaban/net-toolbox
       ports:
       - containerPort: 2000
       securityContext:
           runAsUser: 1000620001
-- Bazhikov
Source: StackOverflow