Back

K8s_Clientset02

ClientSet —— in cluster

out of cluster 是通过集群的配置文件让外部的应用可以操作集群内的资源对象, in cluster 本身是把程序作为一个 pod 运行在集群内部,通过 RBAC 来授权使其能够获取集群的资源对象。

一,大致流程

编写好 go 程序,编译为二进制文件,打包成镜像并推送,然后开启 pod 运行镜像同时需要授予权限,使其有权获取资源信息。

二,编写程序

1, mian.go

package main

import (
	"context"
	"fmt"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

func main() {
	// creates the in-cluster config
	config, err := rest.InClusterConfig()
	if err != nil {
		panic(err.Error())
	}

	// create the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	// get pod
	pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		panic(err.Error())
	}
	for _, pod := range pods.Items {
		fmt.Printf("pod.name:%v\n", pod.Name)
	}
}

2, Dockerfile

# 基础镜像
FROM debian

# 把当前目录下编译得到的二进制 app 复制到工作目录 /app 下 
COPY ./app /app

# 执行工作目录里的 app
ENTRYPOINT /app

# 文件名一定是 Dockerfile ,不要任何后缀,也不要全小写

3, 编译二进制文件

$ go build -o ./app . 

4, 打包镜像

$ docker build . -t app

5, 给镜像加 tag

docker tag **** bocloud-bj.io:5000/app:1.0
// **** 是镜像 ID

6, 推送镜像

docker push bocloud-bj.io:5000/app:1.0

三,开启 pod ,运行 image

1, 给 pod 授权 在 ClusterRole 里定义 pod 有哪些权利,再用 ClusterRoleBinding 去绑定 ClusterRole 和 service account,SA 会为 pod 里的进程提供必要的身份证明。


  1. ClusterRole.yaml
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: pod-get
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
  1. ClusterRoleBinding.yaml
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: pod-get-rbac
subjects:
- kind: ServiceAccount
  namespace: default
  name: clientset-sa
roleRef:
  kind: ClusterRole
  name: pod-get
  apiGroup: rbac.authorization.k8s.io
  1. sa.yaml
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: clientset-sa
  namespace: default
  1. deploy.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: clientset-deploy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: incluster
  template:
    metadata:
      labels:
        app: incluster
    spec:
      containers:
      - name: webhook
        image: bocloud-bj.io:5000/app:1.0
        imagePullPolicy: Always
      serviceAccountName: clientset-sa

四,打印日志

$ kubectl logs ****
// **** 是 pod_id

[centos@ml-k8s-1 ~]$ kubectl logs clientset-deploy-854d7f648c-gcj4v
pod.name:nfs-client-provisioner-6d9b86b854-pcb9v
pod.name:webhook-deploy-854d7f648c-gcj4v
pod.name:coredns-545d6fc579-2kn79
pod.name:coredns-545d6fc579-mpzqg
pod.name:etcd-ml-k8s-1.novalocal
pod.name:fabric-node-2gnjf
pod.name:fabric-node-s92ds

// Note: 因为节点是 Linux 系统,所以在编译二进制 app 时也要在 Linux 环境下。

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy