【kubernetes的基本API操作】

  • A+
所属分类:运维 kubernetes

API

每次创建新的namespace,都会生成一个名为default的serviceAccount,同时会生成一个token,名为default-token-xxxxx

sa就相当于该Namespace下的一个账户

查看集群支持的api版本

[root@ysla manifests]# kubectl api-versions
admissionregistration.k8s.io/v1
apiextensions.k8s.io/v1
apiregistration.k8s.io/v1
apps/v1
authentication.k8s.io/v1
authorization.k8s.io/v1
autoscaling/v1
autoscaling/v2
......

查看默认 ServiceAccount

[root@ysla ~]# kubectl get sa
NAME      SECRETS   AGE
default   1         21d

sa即ServiceAccount的缩写

[root@ysla ~]# kubectl get serviceaccount
NAME      SECRETS   AGE
default   1         21d

ServiceAccount在k8s里账号的概念,下面是更详细的查看,绑定了一个default-token-lbv9p的namespace

[root@ysla ~]# kubectl get sa default -o yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: "2022-03-24T03:01:17Z"
  name: default
  namespace: default
  resourceVersion: "411"
  uid: 58639dbd-7486-4c03-a492-c62f612cca96
secrets:
- name: default-token-lbv9p

根据命令查看secrets

[root@ysla ~]# kubectl get secrets
NAME                  TYPE                                  DATA   AGE
default-token-lbv9p   kubernetes.io/service-account-token   3      21d

[root@ysla ~]# kubectl get secrets default-token-lbv9p
NAME                  TYPE                                  DATA   AGE
default-token-lbv9p   kubernetes.io/service-account-token   3      21d

跟上-oyaml可以根据yaml格式输出,可以看到secrets里边存储了ca证书,其token 存储于 secret 中 ,token里描述了集群里的一些认证信息。可以通过token的权限去调用k8s集群。

[root@ysla ~]# kubectl get secrets default-token-lbv9p -oyaml
apiVersion: v1
data:
  ca.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1ETXlOREF6TURBME4xb1hEVE15TURNeU1UQXpNREEwTjFvd0ZURVRNQkVHQTFVR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enFUM054UlNzVWx4d0VGbm9zRzJPVjQ4TWVHZWdIQm5FeTdHdkQwejk3YWs3TFZuZ05NTzB0a3h0NnV6c3N2ZE1vUExRcndWYzNncHNZcjdlcE9KRHE5d1JHQ1A1ZWtOQi1sb0F3TmN0T0RqVEpGS2lTSFNQQjZ4akRLTC1KRDUwZVM2S0FleENiNWRGSUtxQVNqY0pjeG9jekJfeUpMM1cySG9sOGJRbDQwR3RVMVFfQlJnRlViNm1RUkpHR1YwajZIQVNtQ1prZlV2NmRVZXFPZHVTc0VwdmVQMDJXMlJ5Q180b0djY2pTWkpHb3VoR3dQQUVqWEk2Z09UNEctdlZOYXg2LTB5NmhCQ1VQRF85cjdHeG9R
kind: Secret
metadata:
  annotations:
    kubernetes.io/service-account.name: default
    kubernetes.io/service-account.uid: 58639dbd-7486-4c03-a492-c62f612cca96
  creationTimestamp: "2022-03-24T03:01:17Z"
  name: default-token-lbv9p
  namespace: default
  resourceVersion: "408"
  uid: 84e7efe6-6841-436e-a6b7-0cca69d29f0b
type: kubernetes.io/service-account-token

赋予 ServiceAccount 权限

使用如下命令给该用户分配该Namespace的管理员权限,赋予 ServiceAccount 权限

 kubectl create rolebinding admin --clusterrole=admin -- serviceacount=default:default --namespace=default
 
rolebinding.rbac.authorization.k8s.io/admin created

获取ServiceAccount的token

[root@ysla ~]# TOKEN=$(kubectl describe secret $(kubectl get secrets | grep default | cut -f1 -d ' ')| grep -E '^token' | cut -f2 -d':' |tr -d ' ')
[root@ysla ~]# echo $TOKEN
eyJhbGciOiJSUzI1NiIsImtpZCI6Ik9oR0pra1VUTFZ6WHVxSjR1bUQ0NExKdmV3MEMwTkc3TXptZVJyYVBENHMifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRlZmF1bHQtdG9rZW4tbGJ2OXAiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjU4NjM5ZGJkLTc0ODYtNGMwMy1hNDkyLWM2MmY2MTJjY2E5NiIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRlZmF1bHQifQ.TuUUR51gehEIK-3Q1-O8MYiAwO75j5ReTIFZSI4X7XPY2JskQKKifUmXIPYo6vHzqT3NxRSsUlxwEFnosG2OV48MeGegHBnEy7GvD0z97ak7LVngNMO0tkxt6uzssvdMoPLQrwVc3gpsYr7epOJDq9wRGCP5ekNB-loAwNctODjTJFKiSHSPB6xjDKL-JD50eS6KAexCb5dFIKqASjcJcxoczB_yJL3W2Hol8bQl40GtU1Q_BRgFUb6mQRJGGV0j6HASmCZkfUv6dUeqOduSsEpveP02W2RyC_4oGccjSZJGouhGwPAEjXI6gOT4G-vVNax6-0y6hBCUPD_9r7GxoQ

获取apiserver地址

获取apiserver地址 ,它默认监听在6443端口

[root@ysla ~]# APISERVER=$(kubectl config view | grep https | cut -f 2- -d ":" | tr -d " ")
[root@ysla ~]# echo $APISERVER
https://172.20.10.3:6443

[root@ysla ~]# ss -lnp | grep 6443
tcp    LISTEN     0      128      :::6443                 :::*                   users:(("kube-apiserver",pid=18142,fd=7))

通过 api 获取该 Namespace 下 Pod 资源对象 (json格式输出)

正常情况下会输出 403 Forbidden 错误,提示 SA 没有权限

[root@ysla ~]# curl $APISERVER/api/v1/namespaces/default/pods --header "Authorization:Bearer $TOKEN" --insecure

{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "pods is forbidden: User \"system:serviceaccount:default:default\" cannot list resource \"pods\" in API group \"\" in the namespace \"default\"",
  "reason": "Forbidden",
  "details": {
    "kind": "pods"
  },
  "code": 403

显示k8s集群中的所有api资源信息

[root@ysla ~]# kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationController
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevision
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v2                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1                               true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
endpointslices                                 discovery.k8s.io/v1                    true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta2   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta2   false        PriorityLevelConfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1                              true         PodDisruptionBudget
podsecuritypolicies               psp          policy/v1beta1                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
csistoragecapacities                           storage.k8s.io/v1beta1                 true         CSIStorageCapacity
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment

w3cjava

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: