curl 訪問k8s api


https://www.cnblogs.com/tylerzhou/p/11094872.html

 

下載jq 

chmod +x jq
mv jq /usr/bin/

 

啟用非安全端口

kubectl proxy --port=8080

 查看默認namespace pod列表

 curl localhost:8080/api/v1/namespaces/default/pods/ | jq -r '.items[].metadata.name'

 

HTTPS訪問

創建一個namespace

kubectl create ns  test

 

創建role

kubectl create role pods-reader --verb=get,list,watch --resource=pods --namespace=test

 

創建rolebinding

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: default-role-binding
  namespace: test
subjects:
  - kind: ServiceAccount 
    name: default
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

 

創建一個帶有curl的測試pod

apiVersion: apps/v1
kind: Deployment
metadata:
  name: centos
  namespace: test
spec:
  replicas: 1
  selector:
    matchLabels:
      name: centos
  template:
    metadata:
      labels:
        name: centos
    spec:
      nodeName: master
      containers:
      - image: centos:7
        imagePullPolicy: Never
        name: centos
        command:
        - /bin/sh
        - -c
        - tail -f /dev/null

 

結果測試:

curl --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt --header "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)"  https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT/api/v1/namespaces/$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace)/pods

或者

TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
curl --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt -H "Authorization: Bearer $TOKEN" -s  https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT/api/v1/namespaces/default/pods/

 

 

使用已有的token訪問

 

TOKEN=$(kubectl describe secrets $(kubectl get secrets -n kube-system |grep admin |cut -f1 -d ' ') -n kube-system |grep -E '^token' |cut -f2 -d':'|tr -d '\t'|tr -d ' ')

APISERVER=$(kubectl config view |grep server|cut -f 2- -d ":" | tr -d " ")

 

訪問kube-system下pod

curl -H "Authorization: Bearer $TOKEN" $APISERVER/api/v1/namespaces/default/pods/ --insecure 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM