K8s-通过URL访问模式

背景

大多情况下,一般操作K8s资源都会使用SDK模式,比如client-go

但是其实还支持原生的URL访问模式

几种模式

kubectl

# 启动代理程序
kubectl proxy --port=8080 &

# 查看 http 模式
curl http://localhost:8080/api/ '{"versions": ["v1"]}'

curl(https)

  1. 创建管理员
cat << EOF > CreateServiceAccountRoleBinding.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: admin-user
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: admin-user
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: admin-user
namespace: kube-system
EOF
  1. 创建
$ kubectl apply -f CreateServiceAccountRoleBinding.yaml
$ kubectl get sa -n kube-system admin-user
  1. 获取token
kubectl describe secret -n kube-system `kubectl get secret -n kube-system|grep admin-user|awk '{print $1}'`|grep '^token:'|awk '{print $2}'
  1. 访问
# 设置token 环境变量
TOKEN=$(kubectl describe secret -n kube-system `kubectl get secret -n kube-system|grep admin-user|awk '{print $1}'`|grep '^token:'|awk '{print $2}')

# -k 允许curl使用非安全的ssl连接并且传输数据(证书不受信)
curl -k --header "Authorization: Bearer $TOKEN" https://192.169.44.154:6443/api

使用证书

$ CACERT=/etc/kubernetes/pki/ca.crt
$ curl --cacert $CACERT --header "Authorization: Bearer $TOKEN" https://192.168.0.113:6443/api

Go代码访问

api大全

示例代码

package main

import (
"crypto/tls"
"fmt"
"io"
"net/http"
)

func main() {
// 忽略严重ssl
client := &http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}}
targetUrl := "https://10.10.102.96:6443/api/v1/namespaces/default/services"

req, _ := http.NewRequest("GET", targetUrl, nil)

req.Header.Add("Authorization", "Bearer xxx")

response, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
s, err := io.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
return
}
sprintf := fmt.Sprintf("%s", s)
fmt.Println(sprintf)
}