Bootstrap

[问题已处理]-kubectl config view 没数据

导语:今天想测试一下client-go,需要服务器上有/root/.kube/config文件

执行命令kubectl config view 没有内容 但是kubectl是没问题的

因为是自己二进制安装的,和kubeadm安装的路径可能不太一致。查看自己kubeadm安装的集群是有这个文件的

生成kubeconfig的配置步骤

生成管理员证书
mkdir /root/TLS/admin
cd /root/TLS/admin

cat > admin-csr.json <<EOF
{
  "CN": "admin",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing",
      "ST": "BeiJing",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

# 把需要用到的key拷贝过来
cp /root/TLS/k8s/ca-key.pem  ./
cp /root/TLS/k8s/ca.pem  ./
cp /root/TLS/k8s/ca-config.json ./

cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes admin-csr.json | cfssljson -bare admin
创建kubeconfig文件
# 设置集群参数
kubectl config set-cluster kubernetes   --server=https://192.168.1.120:6443   --certificate-authority=ca.pem   --embed-certs=true   --kubeconfig=config

# 设置上下文参数
kubectl config set-context default   --cluster=kubernetes   --user=cluster-admin   --kubeconfig=config

# 设置客户端认证参数
kubectl config set-credentials cluster-admin   --certificate-authority=ca.pem   --embed-certs=true   --client-key=admin-key.pem   --client-certificate=admin.pem   --kubeconfig=config

# 设置默认上下文
kubectl config use-context default --kubeconfig=config

设置客户端认证参数时 --certificate-authority=ca.pem ##添加管理员权限,没有这一段则为普通用户

运行client-go的demo测试 官方demo https://github.com/kubernetes/client-go/blob/master/examples/out-of-cluster-client-configuration/main.go 里namespace和pod是写死的 并且是精确匹配 只能测试一下先,后续再学习研究

main.go如下

/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Note: the example only works with the code within the same release/branch.
package main

import (
	"context"
	"flag"
	"fmt"
	"path/filepath"
	"time"

	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	//
	// Uncomment to load all auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth"
	//
	// Or uncomment to load specific auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)

func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	// use the current context in kubeconfig
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	// create the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	for {
		pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
		if err != nil {
			panic(err.Error())
		}
		fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))

		// Examples for error handling:
		// - Use helper functions like e.g. errors.IsNotFound()
		// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
		namespace := "default"
		pod := "sample-1"
		_, err = clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod, metav1.GetOptions{})
		if errors.IsNotFound(err) {
			fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)
		} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
			fmt.Printf("Error getting pod %s in namespace %s: %v\n",
				pod, namespace, statusError.ErrStatus.Message)
		} else if err != nil {
			panic(err.Error())
		} else {
			fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)
		}

		time.Sleep(10 * time.Second)
	}
}
go run main.go

创建不同namespace的kubeconfig文件

参考官方文档

https://kubernetes.io/zh/docs/tasks/access-application-cluster/configure-access-multiple-clusters/#set-the-kubeconfig-environment-variable

https://jimmysong.io/kubernetes-handbook/guide/kubectl-user-authentication-authorization.html

;