当前位置:网站首页>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
边栏推荐
- Check the confession items of 6 yyds
- Chargement de l'image pyqt après décodage et codage de l'image
- Go web programming practice (2) -- process control statement
- 基本IO接口技术——微机第七章笔记
- Cardinality sorting (detailed illustration)
- MySQL learning record (4)
- qwb2018_ core kernel_ rop
- It is said that this year gold three silver four has become gold one silver two..
- Jar package startup failed -mysql modify the default port number / set password free enter
- Blue Bridge Cup Eliminate last one (bit operation, code completion)
猜你喜欢
[shutter] shutter gesture interaction (click event handling | click OnTap | double click | long press | click Cancel | press ontapdown | lift ontapup)
Three chess games
Pip install whl file Error: Error: … Ce n'est pas une roue supportée sur cette plateforme
One week dynamics of dragon lizard community | 2.07-2.13
MySQL learning record (8)
MySQL learning record (2)
Off chip ADC commissioning record
How does esrally perform simple custom performance tests?
D4:非成对图像去雾,基于密度与深度分解的自增强方法(CVPR 2022)
qwb2018_ core kernel_ rop
随机推荐
Market trend report, technical innovation and market forecast of China's Micro pliers
Import a large amount of data to redis in shell mode
MySQL learning record (8)
D4:非成对图像去雾,基于密度与深度分解的自增强方法(CVPR 2022)
China's log saw blade market trend report, technological innovation and market forecast
Check the confession items of 6 yyds
Accounting regulations and professional ethics [16]
VictoriaMetrics 简介
关于测试用例
It is said that this year gold three silver four has become gold one silver two..
Physical layer cables and equipment
Construction and maintenance of business websites [4]
Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source
System (hierarchical) clustering method and SPSS implementation
[shutter] shutter layout component (Introduction to layout component | row component | column component | sizedbox component | clipoval component)
[shutter] shutter layout component (opacity component | clipprect component | padding component)
Market trend report, technical dynamic innovation and market forecast of China's low gloss instrument
Cloud computing technology [1]
Welfare, let me introduce you to someone
Free open source web version of xshell [congratulations on a happy new year]