kubectl 的高效用法


用好 kubectl 命令可以极大的提高工作效率,以下所有都不需要从互联网获取答案,直接使用命令就可以完成。

  • 快速查阅 kubectl 命令操作各种资源的详细示例
  • 快速生成 yaml 文件主干,不用记忆字段
  • 快速查阅针对字段的详细解释以及默认值大小

以下是几个比较重要的基础命令,敲的多了就可以做到融会贯通。

可用于查看资源协议,版本,组,命名空间,短名称等信息,尤其是快速了解 CRD 资源的定义。

$ 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
agents                            agent        agent.k8s.elastic.co/v1alpha1          true         Agent
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
...

路由搜索,可用于 api 调试。

$ kubectl api-versions
admissionregistration.k8s.io/v1
agent.k8s.elastic.co/v1alpha1
apm.k8s.elastic.co/v1
apm.k8s.elastic.co/v1beta1
apps/v1
maps.k8s.elastic.co/v1alpha1
metrics.k8s.io/v1beta1
networking.k8s.io/v1
node.k8s.io/v1
node.k8s.io/v1beta1
operator.tigera.io/v1
policy/v1
policy/v1beta1
projectcalico.org/v3
rbac.authorization.k8s.io/v1
scheduling.k8s.io/v1
v1
...

在知道 secret 的情况下使用如下方案:

curl -k -H "Authorization: Bearer $TOKEN" https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces
提示

以上环境变量在 pod 内部可以直接读取,或者直接访问 apiserver 暴露在外的 LB

/ # env |grep KUBER
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_SERVICE_PORT=443
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_HOST=10.96.0.1

获取 serviceacccountbase64 token 值。

kubectl get secret secret-name -n namespace-name -o jsonpath='{.data.token}' | base64 -d

也可以指定证书访问

curl -k --cacert=/etc/kubernetes/pki/ca.crt  --key=/etc/kubernetes/pki/ca.key  "https://127.0.0.1:6443/api/v1/namespaces"

kubectl  get --raw "/api/v1/nodes/k-node-01/proxy/metrics/cadvisor"

打印资源的某个字段及查看详细解释,建议用好该命令,可以不用再记忆某个资源的 yaml 字段定义。

$ kubectl explain pod.spec.nodeName
KIND:     Pod
VERSION:  v1

FIELD:    nodeName <string>

DESCRIPTION:
     NodeName is a request to schedule this pod onto a specific node. If it is
     non-empty, the scheduler simply schedules this pod onto that node, assuming
     that it fits resource requirements.

注意

字段按照 jsonPath 格式进行拼接。另外可以指定资源的版本信息,像下面这样:

kubectl explain --api-version=autoscaling/v2beta2 HorizontalPodAutoscaler.spec.behavior
kubectl explain --api-version=apps/v1 Deployment.spec

你可以使用 --dry-run=client 参数来预览而不真正提交即将下发到集群的对象实例。

检查 kubectl 命令是否正确

$ kubectl create namespace  app  --dry-run=client
namespace/app created (dry run)

利用预执行,生成 yaml 的主框架,再慢慢丰富追加其他字段。

$ kubectl  run nginx-kusc00401 --image=nginx:1.14.2 --overrides='{"spec": {"nodeSelector": {"disk": "ssd"}}}' --dry-run=client  -o yaml | tee pod.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: nginx-kusc00401
  name: nginx-kusc00401
spec:
  containers:
  - image: nginx:1.14.2
    name: nginx-kusc00401
    resources: {}
  dnsPolicy: ClusterFirst
  nodeSelector:
    disk: ssd
  restartPolicy: Always
status: {}

help 用来查看某个子命令的具体用法。该命令可以展示各种资源操作的详细例子。

$ kubectl help create
Create a resource from a file or from stdin.

 JSON and YAML formats are accepted.

Examples:
  # Create a pod using the data in pod.json
  kubectl create -f ./pod.json

  # Create a pod based on the JSON passed into stdin
  cat pod.json | kubectl create -f -

  # Edit the data in docker-registry.yaml in JSON then create the resource using the edited data
  kubectl create -f docker-registry.yaml --edit -o json

Available Commands:
  clusterrole         Create a cluster role
  clusterrolebinding  Create a cluster role binding for a particular cluster role
  configmap           Create a config map from a local file, directory or literal value
  cronjob             Create a cron job with the specified name
  deployment          Create a deployment with the specified name
  ingress             Create an ingress with the specified name
  job                 Create a job with the specified name
  namespace           Create a namespace with the specified name
  poddisruptionbudget Create a pod disruption budget with the specified name
  priorityclass       Create a priority class with the specified name
  quota               Create a quota with the specified name
  role                Create a role with single rule
  rolebinding         Create a role binding for a particular role or cluster role
  secret              Create a secret using specified subcommand
  service             Create a service using a specified subcommand
  serviceaccount      Create a service account with the specified name

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run='none': Must be "none", "server", or "client". If client strategy, only print the object that would be
sent, without sending it. If server strategy, submit server-side request without persisting the resource.
      --edit=false: Edit the API resource before creating
      --field-manager='kubectl-create': Name of the manager used to track field ownership.
  -f, --filename=[]: Filename, directory, or URL to files to use to create the resource
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file.
      --raw='': Raw URI to POST to the server.  Uses the transport specified by the kubeconfig file.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
  -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
      --show-managed-fields=false: If true, keep the managedFields when printing objects in JSON or YAML format.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --validate=true: If true, use a schema to validate the input before sending it
      --windows-line-endings=false: Only relevant if --edit=true. Defaults to the line ending native to your platform.

Usage:
  kubectl create -f FILENAME [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

注意kubectl help createkubectl create –help 等价。