当前位置:网站首页>How do I access the kubernetes API?
How do I access the kubernetes API?
2022-07-02 21:43:00 【MyySophia】
What is? kube-apiserver
k8s API Server Provides k8s Various resource objects (pod,RC,Service etc. ) Add, delete, modify, and search for watch etc. HTTP Rest Interface , It's the data bus and data center of the whole system .
kubernetes API Server The function of :
Cluster management is provided REST API Interface ( Including authentication authorization 、 Data validation and cluster state change );
Provide a hub for data interaction and communication between other modules ( Other modules pass API Server Query or modify data , Only API Server Just direct operation etcd);
It's the gateway to resource quota control ;
It has a complete cluster security mechanism .
How to access the kubernetes API
majority K8S API The type of resource is “objects”, Represents a concrete example of a concept on a cluster , Such as pod or namespace. minority API The type of resource is virtual, Usually represents an operation rather than an object , For example, permission check . All objects will have unique names to allow idempotent creation and retrieval , But if virtual The resource type is not retrievable or does not depend on idempotence , be virtual The resource type may not have a unique name .
1. Use kubectl proxy visit
1.1. Local monitoring
start-up kubectl proxy, Only listen locally without any parameters , It uses http agreement , No credentials are required to access .
Only monitor locally .
kubectl proxy
Starting to serve on 127.0.0.1:8001
verification api visit
[[email protected] /etc/kubernetes]#curl http://127.0.0.1:8001/version
{
"major": "1",
"minor": "23",
"gitVersion": "v1.23.8",
"gitCommit": "a12b886b1da059e0190c54d09c5eab5219dd7acf",
"gitTreeState": "clean",
"buildDate": "2022-06-16T05:51:36Z",
"goVersion": "go1.17.11",
"compiler": "gc",
"platform": "linux/amd64"
}
1.2. Network monitoring
start-up kubectl proxy, Use the network card IP, Access from other machines , --accept-hosts=‘^*$’ Means to accept all sources IP, Otherwise, it will show that it is not authorized .
This method can be used for operations inside the cluster , For example, development needs to call pod You can use this way .
[[email protected] ~]#kubectl proxy --address='10.50.10.32' --accept-hosts='^*$' --port=8001
Starting to serve on 10.50.10.32:8001
[[email protected] /spkshare1/Virtualbox VMS]#curl http://10.50.10.32:8001/version
{
"major": "1",
"minor": "23",
"gitVersion": "v1.23.8",
"gitCommit": "a12b886b1da059e0190c54d09c5eab5219dd7acf",
"gitTreeState": "clean",
"buildDate": "2022-06-16T05:51:36Z",
"goVersion": "go1.17.11",
"compiler": "gc",
"platform": "linux/amd64"
}
As long as you have access to 10.50.10.32 All machines can access :
There's a lot of rest API For you to call
Visit one pod There is no problem
Of course, these methods are unsafe , A more secure way is to authenticate access .
2. Direct access api
2.1. Get the cluster name and api Address
[[email protected] /var/log/containers]#kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'
Cluster name Server
kubernetes https://10.50.10.108:6443
# Export its use variables , Can be defined to environment variables , Aspect debugging
export CLUSTER_NAME="kubernetes"
APISERVER=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.server}")
2.2. Use serviceaccount To visit
Service Account:kubernetes Managed accounts , Used to Pod The service process in is accessing Kubernetes Provide identification when you need to .
establish serviceaccount And bind the cluster role cluster-admin
kubectl create serviceaccount sa-chot
kubectl create clusterrolebinding sa-chot-cluster-admin --clusterrole='cluster-admin' --serviceaccount=default:sa-chot
obtain serviceaccount sa-chot Of secret token
token It's fine too export To environment variable , Convenient debugging
TOKEN=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='sa-chot')].data.token}"|base64 -d)
Use token visit api
curl --header "Authorization: Bearer $TOKEN" --insecure -X GET $APISERVER/api/v1/namespaces/dev/pods?limit=1
curl --header "Authorization: Bearer $TOKEN" --insecure -X GET $APISERVER/api/v1/namespaces/default/pods?limit=1
curl --header "Authorization: Bearer $TOKEN" --insecure -X GET $APISERVER/api/v1/namespaces/kube-system/pods?limit=1
serviceaccount Although it is a distinction namespace Of , But it does not affect the use of this token Access all namespace Resources for .
2.3. Use useraccount To visit
- Generally independent of kubernetes User accounts managed by other services .
establish user chot Certificate
openssl genrsa -out chot.key 2048
openssl req -new -key chot.key -out chot.csr -subj "/CN=chot"
openssl x509 -req -in chot.csr -out chot.crt -sha1 -CA ca.crt -CAkey ca.key -CAcreateserial -days 3650
Create the role getpods, Create role binding user chot and role getpods
kubectl create role getpods --verb=get --verb=list --resource=pods
kubectl create rolebinding chot-getpods --role=getpods --user=chot --namespace=default
Verify that the access is normal
curl --cert /etc/kubernetes/pki/chot.crt -X GET $APISERVER/api/v1/namespaces/default/pods?limit=1 --key /etc/kubernetes/pki/chot.key --insecure
Validate users chot No access namespace kube-system Authority
curl --cert /etc/kubernetes/pki/chot.crt -X GET $APISERVER/api/v1/namespaces/kube-system/pods?limit=1 --key /etc/kubernetes/pki/chot.key --insecure
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {
},
"status": "Failure",
"message": "pods is forbidden: User \"chot\" cannot list resource \"pods\" in API group \"\" in the namespace \"kube-system\"",
"reason": "Forbidden",
"details": {
"kind": "pods"
},
"code": 403
}
3. Commonly used api resources
The following are common resources URL route , take /apis/GROUP/VERSION/ Replace with /api/v1/, Then it means foundation API Group
/apis/GROUP/VERSION/RESOURCETYPE
/apis/GROUP/VERSION/RESOURCETYPE/NAME
/apis/GROUP/VERSION/namespaces/NAMESPACE/RESOURCETYPE
/apis/GROUP/VERSION/namespaces/NAMESPACE/RESOURCETYPE/NAME
/apis/GROUP/VERSION/RESOURCETYPE/NAME/SUBRESOURCE
/apis/GROUP/VERSION/namespaces/NAMESPACE/RESOURCETYPE/NAME/SUBRESOURCE
View extension api Resources in the library deployments
curl http://127.0.0.1:8001/apis/extensions/v1beta1/namespaces/kube-system/deployments
View Basics api Resources in the library pods
curl http://127.0.0.1:8001/api/v1/namespaces/kube-system/pods/
3.1. Use watch Continuously monitor changes in resources
curl http://127.0.0.1:8001/api/v1/namespaces/test/pods
"resourceVersion": "2563046"
curl http://127.0.0.1:8001/api/v1/namespaces/test/pods?watch=1&resourceVersion=2563046
3.2. See the former n A resource
curl http://127.0.0.1:8001/api/v1/namespaces/kube-system/pods?limit=1
"continue": "eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjU2NDk2Mywic3RhcnQiOiJjYWxpY28tbm9kZS1jejZrOVx1MDAwMCJ9"
Use continue token Look at the n A resource
curl 'http://127.0.0.1:8001/api/v1/namespaces/kube-system/pods?limit=1&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjU3MTYxMSwic3RhcnQiOiJjYWxpY28ta3ViZS1jb250cm9sbGVycy01Y2JjY2NjODg1LWt2bGRyXHUwMDAwIn0'
4. The type of resources
Resource classification :Workloads,Discovery & LB ,Config & Storage,Cluster,Metadata
Resource objects :Resource ObjectMeta,ResourceSpec,ResourceStatus
Resource operations :create,update(replace&patch),read(get&list&watch),delete,rollback,read/write scale,read/write status
5.Workloads The operation of
If you want to develop a product similar to kuboard Tools for , these REST API Will be very useful .
With pod For example , Introduce workloads apis, The following is a pod Of yaml file
apiVersion: v1
kind: Pod
metadata:
name: pod-example
spec:
containers:
- name: ubuntu
image: ubuntu:trusty
command: ["echo"]
args: ["Hello World"]
5.1. establish pod
POST /api/v1/namespaces/{namespace}/pods
View the current pods
# kubectl -n test get pods
NAME READY STATUS RESTARTS AGE
Use api establish pod
curl --request POST http://127.0.0.1:8001/api/v1/namespaces/test/pods -s -w " Status code is :%{http_code}\n" -o /dev/null -H 'Content-Type: application/yaml' --data 'apiVersion: v1 kind: Pod metadata: name: pod-example spec: containers: - name: ubuntu image: ubuntu:trusty command: ["echo"] args: ["Hello World"]'
Status code is :201
View the current pods
#kubectl -n test get pods
NAME READY STATUS RESTARTS AGE
pod-example 0/1 ContainerCreating 0 4s
Status code
200 Ok
201 Created
202 Accepted
5.2. Delete pod
DELETE /api/v1/namespaces/{namespace}/pods/{name}
View the current pods
kubectl get pods -n test --show-labels
NAME READY STATUS RESTARTS AGE LABELS
pod-example 0/1 CrashLoopBackOff 1 15s <none>
Delete pod pod-example
curl --request DELETE http://127.0.0.1:8001/api/v1/namespaces/test/pods/pod-example -o /dev/null -s -w " Status code is :%{http_code}\n"
Status code is :200
View the current pods
kubectl get pods -n test --show-labels
NAME READY STATUS RESTARTS AGE LABELS
pod-example 0/1 Terminating 2 28s <none>
Status code
200 Ok
202 Accepted
边栏推荐
- pip安裝whl文件報錯:ERROR: ... is not a supported wheel on this platform
- Huawei Hongmeng watch achieves fireworks display effect on New Year's Eve
- [shutter] statefulwidget component (floatingactionbutton component | refreshindicator component)
- Analysis of enterprise financial statements [3]
- Cloud computing technology [1]
- pyqt图片解码 编码后加载图片
- [Yu Yue education] reference materials of analog electronic technology of Nanjing Institute of information technology
- Research Report on market supply and demand and strategy of China's plastic trunking industry
- Spend more time with your computer on this special holiday, HHH
- China plastic box market trend report, technological innovation and market forecast
猜你喜欢
Structure array, pointer and function and application cases
如何防止你的 jar 被反编译?
[zero foundation I] Navicat download link
Welfare, let me introduce you to someone
pip安裝whl文件報錯:ERROR: ... is not a supported wheel on this platform
Baidu sued a company called "Ciba screen"
[shutter] shutter layout component (wrap component | expanded component)
【零基础一】Navicat下载链接
Gbase8s database type
Capacity expansion mechanism of ArrayList
随机推荐
One week dynamics of dragon lizard community | 2.07-2.13
[shutter] statefulwidget component (pageview component)
Pyqt picture decodes and encodes and loads pictures
Research Report on plastic antioxidant industry - market status analysis and development prospect forecast
Structured text language XML
In depth research and investment feasibility report of global and Chinese isolator industry, 2022-2028
【剑指 Offer】56 - I. 数组中数字出现的次数
Huawei Hongmeng watch achieves fireworks display effect on New Year's Eve
How is LinkedList added?
Today, I met a Alipay and took out 35K. It's really sandpaper to wipe my ass. it's a show for me
[shutter] statefulwidget component (create statefulwidget component | materialapp component | scaffold component)
*C语言期末课程设计*——通讯录管理系统(完整项目+源代码+详细注释)
Construction and maintenance of business website [5]
Welfare, let me introduce you to someone
Construction and maintenance of business websites [4]
Unexpectedly, there are such sand sculpture code comments! I laughed
Analysis of neural network
读博士吧,研究奶牛的那种!鲁汶大学 Livestock Technology 组博士招生,牛奶质量监测...
It is said that this year gold three silver four has become gold one silver two..
[shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)