方法1:
pod中的进程读取/var/run/secrets/kubernetes.io/serviceaccount/namespace这个文件
$ cat /var/run/secrets/kubernetes.io/serviceaccount/namespace
default
方法2:
apiVersion:v1kind:Podmetadata:name:dapi-envars-fieldrefspec:containers:-name: test-containerimage:k8s.gcr.io/busyboxcommand:[ "sh", "-c"]args:-while true; doecho -en '\n';
printenv MY_NODE_NAME MY_POD_NAME MY_POD_NAMESPACE;
printenv MY_POD_IP MY_POD_SERVICE_ACCOUNT;
sleep 10;
done;
env:-name: MY_NODE_NAMEvalueFrom:fieldRef:fieldPath:spec.nodeName-name: MY_POD_NAMEvalueFrom:fieldRef:fieldPath:metadata.name-name: MY_POD_NAMESPACEvalueFrom:fieldRef:fieldPath:metadata.namespace-name: MY_POD_IPvalueFrom:fieldRef:fieldPath:status.podIP-name: MY_POD_SERVICE_ACCOUNTvalueFrom:fieldRef:fieldPath:spec.serviceAccountNamerestartPolicy:Never
如上:在资源申明yaml中,增加env字段。namespace的valueFrom指定为metadata.namespace。
然后在进程中,读取你定义的环境变量就可以感知到namespace了。