Kubernetes 完全教程

Kubernetes 的 API Spec 以及安全机制

王渊命 @jolestar

bg


Agenda

  1. Kubernetes 的 API Spec
    • YAML
    • API Spec 概述
    • Label 和 Selector 机制
    • Pod 详解
    • Service/ReplicaSet/Deployment/DaemonSet/StatefulSet/Job/CronJob/ConfigMap
    • Kubernetes API Object 的连带删除机制
  2. Kubernetes 的安全机制
    • 认证(Authentication)
    • 授权(Authorization)
    • Admission Control

YAML 简介

YAML is a human-readable data serialization language. It is commonly used for configuration files, but could be used in many applications where data is being stored or transmitted.

  • 空格缩进表示层级关系,不支持 TAB
  • : 用来分割 key/value
  • - 表示数组元素,每行一个,也可以用方括号([] )和 逗号(,)来区分。
  • 字符串可以不用引号,也支持 “ 和 ‘
  • 可以用 -— 区隔文档,把多个文档合并到同一个文件中
  • 支持多行字符输入,通过 | 保留换行符,或者 > 折叠换行
  • 支持锚点标记(&)和参考标记(*)避免重复
  • # 表示注释
  • 是 json 格式的超集

YAML Example

  1. # Invoice example
  2. receipt: Oz-Ware Purchase Invoice
  3. customer:
  4. given: Dorothy
  5. items:
  6. - part_no: A4786
  7. descrip: Water Bucket (Filled)
  8. price: 1.47
  9. quantity: 4
  10. - part_no: E1628
  11. descrip: High Heeled "Ruby" Slippers
  12. price: 133.7
  13. quantity: 1
  14. bill-to: &id001
  15. street: |
  16. 123 Tornado Alley
  17. Suite 16
  18. city: East Centerville
  19. ship-to: *id001
  20. specialDelivery: >
  21. Follow the Yellow Brick
  22. Road to the Emerald City.

Kubernets API Spec 概述

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: nginx
  5. labels:
  6. app: web
  7. env: prod
  8. annotations:
  9. mydomain.com/custom-extend-key: value
  10. spec:
  11. containers:
  12. - name: nginx
  13. image: nginx:1.7.9
  14. ports:
  15. - containerPort: 80

Kubernetes API Spec

  • apiVersion: Object Schema 版本 (v1,batch/v1,storage.k8s.io/v1)
  • kind: Object Schema 类型(List,Pod,Node,Service)
  • metadata:
    • namespace
    • name
    • uid
    • resourceVersion
    • labels
    • annotations

Kubernetes API Spec

  • spec
  • status

Label 和 Selector

equality/inequality-based

  1. environment = production
  2. tier != frontend

set-based

  1. environment in (production, qa)
  2. tier notin (frontend, backend)
  3. partition
  4. !partition
  1. kubectl get pods -l environment=production,tier=frontend

Pod

  1. Pod 的实现原理(参看预备课)
  2. Pod Spec
  3. Pod 生命周期

Container

  • command/args
  • image/imagePullPolicy: Always, Never, IfNotPresent
  • livenessProbe/readinessProbe: exec,httpGet,tcp
  • resources
  • volumeMounts

Pod Spec

  • apiVersion: core/v1
  • activeDeadlineSeconds/terminationGracePeriodSeconds
  • dnsPolicy: ClusterFirst,ClusterFirstWithHostNet,Default
  • hostNetwork/hostPID/hostIPC
  • initContainers/containers
  • imagePullSecrets
  • serviceAccountName
  • lifecycle: Hooks: postStart/preStop
  • restartPolicy: Always, OnFailure, Never
  • nodeName/nodeSelector
  • tolerations
  • affinity
  • volumes

Pod 生命周期

  • PodStatus
    • phase Pending/Running/Succeeded/Failed/Unknown
    • conditions PodScheduled,Initialized,Ready
    • containerStatuses

Pod 生命周期-创建

第四课:Kubernetes 的 API Spec 以及安全机制 - 图2

https://dzone.com/articles/kubernetes-lifecycle-of-a-pod


PodTemplateSpec

  • metadata
  • spec(PodSpec)

PodDisruptionBudget

  1. apiVersion: policy/v1beta1
  2. kind: PodDisruptionBudget
  3. metadata:
  4. name: zk-pdb
  5. spec:
  6. selector:
  7. matchLabels:
  8. app: zk
  9. maxUnavailable: 1

Service

  • apiVersion: v1
  • spec
    • clusterIP: None/IP
    • externalIPs
    • ports
    • selector
    • externalName
    • type: ExternalName, ClusterIP, NodePort, LoadBalancer

Service

  1. apiVersion: v1
  2. kind: Service
  3. metadata:
  4. labels:
  5. k8s-app: kube-dns
  6. name: kube-dns
  7. namespace: kube-system
  8. spec:
  9. clusterIP: 10.96.0.10
  10. ports:
  11. - name: dns
  12. port: 53
  13. protocol: UDP
  14. targetPort: 53
  15. selector:
  16. k8s-app: kube-dns
  17. type: ClusterIP

selector 只支持 equality-based


Endpoint

  • addresses
  • notReadyAddresses
  • ports
  1. apiVersion: v1
  2. kind: Endpoints
  3. metadata:
  4. name: helloworld
  5. namespace: default
  6. subsets:
  7. - addresses:
  8. - ip: 192.168.100.244
  9. nodeName: i-0elqbqzu
  10. - ip: 192.168.101.247
  11. nodeName: i-7d7zqw6x
  12. ports:
  13. - port: 80
  14. protocol: TCP

ReplicaSet (ReplicationController)

  • apiVersion: apps/v1beta2 (1.8 以前是 extensions/v1beta1)
  • spec
    • minReadySeconds
    • replicas
    • selector
    • template: PodTemplateSpec

Deployment

  • apiVersion: apps/v1beta2 (1.8以前是 apps/v1beta1)
  • spec
    • minReadySeconds
    • paused
    • replicas
    • selector
    • strategy: Recreate/RollingUpdate
      • rollingUpdate.maxSurge
      • rollingUpdate.maxUnavailable
    • revisionHistoryLimit
    • template: PodTemplateSpec

Deployment

  1. apiVersion: apps/v1beta2
  2. kind: Deployment
  3. metadata:
  4. name: nginx-deployment
  5. labels:
  6. app: nginx
  7. spec:
  8. replicas: 3
  9. selector:
  10. matchLabels:
  11. app: nginx
  12. template:
  13. metadata:
  14. labels:
  15. app: nginx
  16. spec:
  17. containers:
  18. - name: nginx
  19. image: nginx:1.7.9
  20. ports:
  21. - containerPort: 80

Deployment Rolling updates

  1. kubectl set image deployment <deployment> <container>=<image>
  2. kubectl rollout status deployment <deployment>
  3. kubectl rollout pause deployment <deployment>
  4. kubectl rollout resume deployment <deployment>
  5. kubectl rollout undo deployment <deployment>

https://kubernetes.io/docs/tutorials/kubernetes-basics/update-intro/


DaemonSet

  • apiVersion: apps/v1beta2 (1.8以前是 extensions/v1beta1)
  • spec
    • minReadySeconds
    • revisionHistoryLimit
    • selector
    • template
    • updateStrategy: RollingUpdate,OnDelete

StatefulSet

  • apiVersion: apps/v1beta2 (1.8以前是 apps/v1beta1)
  • spec
    • podManagementPolicy: OrderedReady,Parallel
    • serviceName
    • replicas
    • revisionHistoryLimit
    • selector
    • template
    • updateStrategy: OnDelete,RollingUpdate
      • rollingUpdate.partition
    • volumeClaimTemplates: PersistentVolumeClaim

StatefulSet

  • Pod Identity
    • ordinal: [0,N)
    • pod name: \$(statefulset name)-\$(ordinal)
    • pod dns: \$(pod name).\$(service name).\$(namespace).svc.cluster.local
  • Storage
    • PersistentVolume Provisioner
    • volumeClaimTemplates 的定义优先级高于 PodTemplate 中的定义
    • PVC 的生命周期独立于 StatefulSet

Job

  • apiVersion: batch/v1
  • spec
    • activeDeadlineSeconds
    • backoffLimit: default 6
    • completions
    • parallelism
    • selector
    • manualSelector
    • template: PodTemplateSpec
      • RestartPolicy: Never,OnFailure

Job

  1. apiVersion: batch/v1
  2. kind: Job
  3. metadata:
  4. name: pi
  5. spec:
  6. template:
  7. metadata:
  8. name: pi
  9. spec:
  10. containers:
  11. - name: pi
  12. image: perl
  13. command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
  14. restartPolicy: Never
  15. backoffLimit: 4

CronJob

  • apiVersion: batch/v1beta1
  • spec
    • concurrencyPolicy: Allow, Forbid, Replace
    • startingDeadlineSeconds
    • successfulJobsHistoryLimit: default 3
    • failedJobsHistoryLimit: default 1
    • jobTemplate: JobTemplateSpec
    • schedule: Cron format
    • suspend

CronJob

  1. apiVersion: batch/v1beta1
  2. kind: CronJob
  3. metadata:
  4. name: hello
  5. spec:
  6. schedule: "*/1 * * * *"
  7. jobTemplate:
  8. spec:
  9. template:
  10. spec:
  11. containers:
  12. - name: hello
  13. image: busybox
  14. args:
  15. - /bin/sh
  16. - -c
  17. - date; echo Hello from the Kubernetes cluster
  18. restartPolicy: OnFailure

ConfigMap

  • apiVersion: v1
  • data: object
    1. kind: ConfigMap
    2. apiVersion: v1
    3. metadata:
    4. name: example-config
    5. namespace: default
    6. data:
    7. examplekey: hello
    8. example.property: |-
    9. property.1=value-1
    10. property.2=value-2
    11. property.3=value-3
  • 使用:env,volume

Kubernetes API Object 的连带删除机制

  • Label/Selector
  • metadata.ownerReferences
  • kubectl delete —cascade=false

Kubernetes 安全机制

  1. 认证(Authentication):Client Certificates, Password, and Plain Tokens, Bootstrap Tokens, JWT Tokens
  2. 授权(Authorization):ABAC, RBAC, Webhook
  3. Admission Control

Kubernetes 安全机制

第四课:Kubernetes 的 API Spec 以及安全机制 - 图3


Kubernetes 的认证(Authentication)

  1. user (normal users, service accounts)
  2. group

Kubernetes 的认证(Authentication)

  • X509 Client Certs
    1. openssl req -new -key jbeda.pem -out jbeda-csr.pem -subj "/CN=jbeda/O=app1/O=app2"
    https://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster/
  • Static Token File
    • apiserver —token-auth-file=SOMEFILE
      1. token,user,uid,"group1,group2,group3"
      1. Authorization: Bearer token-xxxx
  • Static Password File
    • apiserver —basic-auth-file=SOMEFILE
      1. password,user,uid,"group1,group2,group3"
      1. Authorization: Basic BASE64ENCODED(USER:PASSWORD)

Kubernetes 的认证(Authentication)

  • OpenID Connect Tokens
  • Webhook Token Authentication
    • apiserver
      • —authentication-token-webhook-config-file
      • —authentication-token-webhook-cache-ttl
  • Authenticating Proxy
    • —requestheader-username-headers
    • —requestheader-group-headers

ServiceAcccount

  • 一种将身份和资源绑定的机制(AWS Role, GCE ServiceAccount)
  • 通过以下机制实现
    • ServiceAccount admission
      • 自动检查或者设置 pod 的 serviceAccountName
      • 增加 token volume 并且挂载(/var/run/secrets/kubernetes.io/serviceaccount)
    • Token controller
    • Service account controller
    • client sdk 自动读取固定路径下的 token
      • 支持关联 imagePullSecret

Kubernetes 的授权(Authorization)

授权的主要要素

  • User
  • Group
  • Verb: get, list, create, update, patch, watch, proxy, redirect, delete, deletecollection
  • Resource
  • Namespace
  • API
  • API Group

Kubernetes Authorization Modules

  • Node
  • ABAC
    1. {"apiVersion": "abac.authorization.kubernetes.io/v1beta1", "kind": "Policy",
    2. "spec": {"user": "alice", "namespace": "*", "resource": "*", "apiGroup": "*"}}
  • RBAC
  • Webhook

Kubernetes RBAC Authorization

Role/ClusterRole

  1. kind: Role
  2. apiVersion: rbac.authorization.k8s.io/v1
  3. metadata:
  4. namespace: default
  5. name: pod-reader
  6. rules:
  7. - apiGroups: [""]
  8. resources: ["pods"]
  9. verbs: ["get", "watch", "list"]
  1. kind: ClusterRole
  2. apiVersion: rbac.authorization.k8s.io/v1
  3. metadata:
  4. name: secret-reader
  5. rules:
  6. - apiGroups: [""]
  7. resources: ["secrets"]
  8. verbs: ["get", "watch", "list"]

Kubernetes RBAC Authorization

RoleBinding/ClusterRoleBinding

  1. kind: RoleBinding/ClusterRoleBinding
  2. apiVersion: rbac.authorization.k8s.io/v1
  3. metadata:
  4. name: read-pods
  5. namespace: default
  6. subjects:
  7. - kind: User/Group/ServiceAccount
  8. name: jane
  9. apiGroup: rbac.authorization.k8s.io
  10. roleRef:
  11. kind: Role/ClusterRole
  12. name: pod-reader
  13. apiGroup: rbac.authorization.k8s.io

Admission Control


演示

  1. DaemonSet https://github.com/QingCloudAppcenter/kubernetes/blob/master/k8s/addons/kube-proxy
  2. Service 以及 Deployment 滚动升级
    1. wget https://raw.githubusercontent.com/jolestar/kubernetes-complete-course/master/example/helloworld.yaml
    2. kubectl apply -f helloworld.yaml
    3. kubectl scale --replicas=6 deployment/helloworld
    4. curl -H "accept: application/yaml" helloworld/status
    5. kubectl get replicaset
    6. kubectl set image deployment/helloworld web=jolestar/go-probe:v0.2
    7. kubectl rollout status deployment/helloworld
    8. kubectl rollout pause deployment/helloworld
    9. kubectl get replicaset
    10. kubectl rollout resume deployment/helloworld
    11. kubectl rollout undo deployment/helloworld
    12. curl -H "accept: application/yaml" helloworld/status
  3. 将 pod 从 Deployment 摘除
  4. RBAC 以及 ServiceAccount 的使用 https://github.com/QingCloudAppcenter/kubernetes/tree/master/k8s/addons/dashboard

演示

  • 通过 StatefulSet 部署 zookeeper 集群
    https://kubernetes.io/docs/tutorials/stateful-application/zookeeper/
    1. wget https://raw.githubusercontent.com/jolestar/kubernetes-complete-course/master/example/zookeeper_mini.yaml
    2. kubectl apply -f zookeeper_mini.yaml
    3. kubectl exec zk-0 -- cat /opt/zookeeper/conf/zoo.cfg
    4. kubectl exec zk-0 -- /opt/zookeeper/bin/zkCli.sh create /test "test"
    5. kubectl exec zk-0 -- cat /opt/zookeeper/bin/start-zookeeper|less
    6. kubectl exec zk-0 -- /opt/zookeeper/bin/zkCli.sh create ls /
    7. kubectl exec zk-1 -- /opt/zookeeper/bin/zkCli.sh create ls /
    8. kubectl delete -f zookeeper_mini.yaml
    9. kubectl get pvc
    10. kubectl get pv
    11. kubectl apply -f zookeeper_mini.yaml
    12. kubectl exec zk-0 -- /opt/zookeeper/bin/zkCli.sh create ls /

总结

对 Kubernetes 的 Spec 以及安全机制有一个整体的理解

  1. Kubernetes 的描述文件能做什么,如何将当前系统组件通过 Kubernetes 中的对象描述出来
  2. Kubernetes 提供了哪些安全机制,如何和当前内部权限系统整合
  3. Kubernetes 提供的扩展插件能做什么,如何通过插件在集群全局配置策略,约束和规范应用的部署行为

关于 API Spec 中的版本以及支持的属性,参看 Api Reference 1.7 1.8
下节课:通过应用案例解析 kubernetes 中的 pod 放置策略,autoscale 等。


作业

  1. 通过 StatefulSet 部署 kafka,参看 https://github.com/kow3ns/kubernetes-kafka, 并理解如何利用 Kubernetes 的能力部署分布式系统。
  2. 通过证书生成工具,生成一个普通用户证书并让 Kubernetes 批准,然后使用该证书操作集群,而不是默认的 admin 账号。
  3. 思考并尝试通过 Kubernetes 搭建一个日志收集分析系统。

关于我

个人博客: http://jolestar.com
课程 Github:https://github.com/jolestar/kubernetes-complete-course

about


第四课:Kubernetes 的 API Spec 以及安全机制 - 图5