当前位置:网站首页>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
边栏推荐
- Research Report on market supply and demand and strategy of microplate instrument industry in China
- Construction and maintenance of business website [1]
- A river of spring water flows eastward
- [C language] [sword finger offer article] - replace spaces
- PIP audit: a powerful security vulnerability scanning tool
- Plastic granule Industry Research Report - market status analysis and development prospect forecast
- Physical layer cables and equipment
- Get weekday / day of week for datetime column of dataframe - get weekday / day of week for datetime column of dataframe
- How to prevent your jar from being decompiled?
- [dynamic planning] p1220: interval DP: turn off the street lights
猜你喜欢
Investment strategy analysis of China's electronic information manufacturing industry and forecast report on the demand outlook of the 14th five year plan 2022-2028 Edition
Today, I met a Alipay and took out 35K. It's really sandpaper to wipe my ass. it's a show for me
Unexpectedly, there are such sand sculpture code comments! I laughed
MySQL learning record (2)
[shutter] shutter page Jump (route | navigator | page close)
Capacity expansion mechanism of ArrayList
*C语言期末课程设计*——通讯录管理系统(完整项目+源代码+详细注释)
[CV] Wu Enda machine learning course notes | Chapter 12
D4: unpaired image defogging, self enhancement method based on density and depth decomposition (CVPR 2022)
The neo4j skill tree was officially released to help you easily master the neo4j map database
随机推荐
关于测试用例
2019 Nanchang (relive the classic)
MySQL learning notes (Advanced)
Research Report on market supply and demand and strategy of China's atomic spectrometer industry
如何访问kubernetes API?
[shutter] statefulwidget component (pageview component)
Browser - clean up the cache of JS in the page
Free open source web version of xshell [congratulations on a happy new year]
Construction and maintenance of business websites [9]
Construction and maintenance of business websites [7]
China's log saw blade market trend report, technological innovation and market forecast
~91 rotation
Hot backup routing protocol (HSRP)
[shutter] shutter page Jump (route | navigator | page close)
Share the easy-to-use fastadmin open source system - Installation
Golang embeds variables in strings
Basic IO interface technology - microcomputer Chapter 7 Notes
Image segmentation using pixellib
Accounting regulations and professional ethics [18]
【剑指 Offer】56 - I. 数组中数字出现的次数