Kubernetes编程——通过命令行使用 API
通过命令行使用 API
长话短说,我们将使用以 batch API 组为例来讲 cli 相关的操作。
首先,需要在终端运行下面的命令:
[root@localhost ~]# kubectl proxy --port=8089 Starting to serve on 127.0.0.1:8089
这个命令把 kubernetes API 服务代理到了本地,并处理了有关身份认证和授权相关的逻辑。这样我们就可以直接使用 HTTP 来发送请求,并接收返回的 JSON 数据。再打开一个终端,尝试查询下 v1:
[root@localhost ~]# curl http://127.0.0.1:8089/apis/batch/v1 { "kind": "APIResourceList", "apiVersion": "v1", "groupVersion": "batch/v1", "resources": [ { "name": "jobs", "singularName": "", "namespaced": true, "kind": "Job", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ], "categories": [ "all" ], "storageVersionHash": "mudhfqk/qZY=" }, { "name": "jobs/status", "singularName": "", "namespaced": true, "kind": "Job", "verbs": [ "get", "patch", "update" ] } ] }
也不是必须要使用 curl 和 kubectl proxy 命令才能访问 kubernetes 的 HTTP API,还可以使用 kubectl get --raw 命令,比如 curl http://127.0.0.1:8089/apis/batch/v1 改为 kubectl get --raw /apis/batch/v1。
[root@localhost ~]# kubectl get --raw /apis/batch/v1 {"kind":"APIResourceList","apiVersion":"v1","groupVersion":"batch/v1","resources":[{"name":"jobs","singularName":"","namespaced":true,"kind":"Job","verbs":["create","delete","deletecollection","get","list","patch","update","watch"],"categories":["all"],"storageVersionHash":"mudhfqk/qZY="},{"name":"jobs/status","singularName":"","namespaced":true,"kind":"Job","verbs":["get","patch","update"]}]}