简体   繁体   English

如何使用 go-client 在 k8s 中访问我的 pod

[英]How to access my pod in k8s using go-client

I am using go-client to access k8s resources in my environment.我正在使用 go-client 访问我环境中的 k8s 资源。 There are APIs to get/list pods, namespaces, etc.有用于获取/列出 pod、名称空间等的 API。

How do I access the pod that I am currently running on?如何访问我当前正在运行的 pod?

You can Expose Pod Information to Containers Through Environment Variables using pod fields :您可以使用pod 字段通过环境变量向容器公开 Pod 信息

apiVersion: v1
kind: Pod
metadata:
  name: dapi-envars-fieldref
spec:
  containers:
    - name: test-container
      ...
      ...
      env:
        - name: MY_NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: MY_POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MY_POD_SERVICE_ACCOUNT
          valueFrom:
            fieldRef:
              fieldPath: spec.serviceAccountName
  restartPolicy: Never

then simply look up these env vars in your Go code:然后只需在您的 Go 代码中查找这些环境变量:

log.Printf("MY_POD_NAME: %q", os.Getenv("MY_POD_NAME"))

The Kube.netes client-go supplies API to access pods, and the CoreV1 package gives an API to get All Pods see the documentation https://pkg.go.dev/k8s.io/client-go/kube.netes/typed/core/v1#CoreV1Client.Pods Kube.netes client-go 提供 API 来访问 pod,而 CoreV1 package 提供 API 来获取所有 Pod 请参阅文档https://pkg.go.dev/k8s.io/clientes.go/kube /core/v1#CoreV1Client.Pods

You can easily filter or fetch Pods by Namespace, Label or Query,您可以通过命名空间、Label 或查询轻松过滤或获取 Pod,

See a sample code to get all pods in Namespace.查看示例代码以获取命名空间中的所有 pod。


  config, err := clientcmd.BuildConfigFromFlags("", "PATH to cluster config yaml")
  clientset, err := kubernetes.NewForConfig(config)
  if err != nil {
     panic(err.Error())
  }
  // Get all pods in namespace
  pods, err := clientset.CoreV1().Pods("NANESPACE").List(context.TODO(), 
  metav1.ListOptions{})
  if err != nil {
          panic(err.Error())
  }

See the Sample code for getting pods using a label:请参阅使用 label 获取 pod 的示例代码:



 labal := fmt.Sprintf("LABLE-NAME=%s", "SOME LABEL VALUE")
    ap1 := sm.clientset.CoreV1()
    pods, _ := ap1.Pods(namespace).List(context.Background(), 
         metav1.ListOptions{LabelSelector: labal})
    pods_num := len(pods.Items)
    fmt.Printf("Found the following number of Pods: %d\n", pods_num)
    for i, pod := range pods.Items {
        fmt.Printf("[%2d] %s, Phase: %s, Created: %s, HostIP: %s\n", i, 
              pod.GetName(), string(pod.Status.Phase), 
              pod.GetCreationTimestamp(), 
              string(pod.Status.HostIP))
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM