在k8s中如何使用代码获取当前namespace

有两种方法
一、通过环境变量获取
https://kubernetes.io/zh/docs/tasks/inject-data-application/environment-variable-expose-pod-information/
添加字段

 env:
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace

主要的deployment的yaml文件如下

kind: Deployment
apiVersion: apps/v1
metadata:
  name: fluentbit-operator
  namespace: kubesphere-logging-system
  labels:
    app.kubernetes.io/component: operator
    app.kubernetes.io/name: fluentbit-operator
  annotations:
    deployment.kubernetes.io/revision: '5'
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/component: operator
      app.kubernetes.io/name: fluentbit-operator
  template:
    metadata:
      creationTimestamp: null
      labels:
        app.kubernetes.io/component: operator
        app.kubernetes.io/name: fluentbit-operator
    spec:
      containers:
        - name: fluentbit-operator
          image: 'wenchajun/fluentbit-operator:v1.3'
          env:
            - name: MY_POD_NAMESPACE
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.namespace
          resources:
            limits:
              cpu: 100m
              memory: 30Mi

然后在代码中就可以直接获取了

     ns:= os.Getenv("MY_POD_NAMESPACE")
         fmt.Println("my namespace is ",ns)

第二种,直接读取
https://kubernetes.io/zh/docs/tasks/run-application/access-api-from-pod/#directly-accessing-the-rest-api

filePath :="/var/run/secrets/kubernetes.io/serviceaccount/namespace"
        nsRead ,err :=ioutil.ReadFile(filePath)
        if err !=nil {
            return ctrl.Result{}, err
        }  

你可能感兴趣的:(在k8s中如何使用代码获取当前namespace)