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

本文档详细介绍了如何生成kubeconfig文件来访问Kubernetes集群,包括管理员证书的创建、kubeconfig的配置步骤以及client-go的简单示例。通过设置集群、上下文和客户端认证参数,可以成功建立到集群的连接。此外,还提供了创建不同namespace的kubeconfig文件的方法,并给出了一个client-go的demo代码,用于展示如何从外部程序访问集群。
摘要由CSDN通过智能技术生成
导语:今天想测试一下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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爷来辣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值