如何使用Go客户端访问我的Kubernetes中的Pod?

huangapple go评论86阅读模式
英文:

How to access my pod in k8s using go-client

问题

我正在使用go-client来访问我的环境中的k8s资源。有一些API可以获取/列出pod、命名空间等。

我如何访问当前正在运行的pod?

英文:

I am using go-client to access k8s resources in my environment. There are APIs to get/list pods, namespaces, etc.

How do I access the pod that I am currently running on?

答案1

得分: 1

您可以使用环境变量将Pod信息传递给容器,具体方法请参考Kubernetes官方文档中的"Expose Pod Information to Containers Through Environment Variables"部分,使用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

然后,在您的Go代码中可以通过查找这些环境变量来使用它们:

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

请注意,以上代码仅为示例,您需要根据实际情况进行适当的修改和调整。

英文:

You can Expose Pod Information to Containers Through Environment Variables using pod fields:

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:

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

答案2

得分: 0

Kubernetes的client-go库提供了访问Pod的API,CoreV1包提供了获取所有Pod的API,可以查看文档:https://pkg.go.dev/k8s.io/client-go/kubernetes/typed/core/v1#CoreV1Client.Pods

你可以通过命名空间、标签或查询来轻松过滤或获取Pod。

以下是一个示例代码,用于获取命名空间中的所有Pod:

config, err := clientcmd.BuildConfigFromFlags("", "集群配置文件的路径")
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
   panic(err.Error())
}
// 获取命名空间中的所有Pod
pods, err := clientset.CoreV1().Pods("命名空间").List(context.TODO(), metav1.ListOptions{})
if err != nil {
    panic(err.Error())
}

以下是使用标签获取Pod的示例代码:

label := fmt.Sprintf("标签名称=%s", "某个标签的值")
ap1 := sm.clientset.CoreV1()
pods, _ := ap1.Pods(namespace).List(context.Background(), metav1.ListOptions{LabelSelector: label})
pods_num := len(pods.Items)
fmt.Printf("找到以下数量的Pod:%d\n", pods_num)
for i, pod := range pods.Items {
    fmt.Printf("[%2d] %s,阶段:%s,创建时间:%s,主机IP:%s\n", i, pod.GetName(), string(pod.Status.Phase), pod.GetCreationTimestamp(), string(pod.Status.HostIP))
}
英文:

The Kubernetes 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/kubernetes/typed/core/v1#CoreV1Client.Pods

You can easily filter or fetch Pods by Namespace, Label or Query,

See a sample code to get all pods in Namespace.


  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:



 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))
     }

huangapple
  • 本文由 发表于 2022年1月8日 00:50:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70624571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定