3.2 Kubernetes API Server深度剖析:RESTful API、认证授权、准入控制机制
引言
API Server是Kubernetes的核心组件,所有组件都通过API Server进行通信。深入理解API Server的RESTful API、认证授权和准入控制机制,是掌握Kubernetes的关键。本文将详细解析API Server的工作原理。
一、API Server概述
1.1 API Server的作用
- Kubernetes的统一入口
- RESTful API服务
- 数据验证和转换
- 认证授权
- 准入控制
1.2 API Server架构
Client Request │ ▼ ┌──────────────┐ │ Authentication│ 认证 └──────┬───────┘ │ ▼ ┌──────────────┐ │ Authorization │ 授权 └──────┬───────┘ │ ▼ ┌──────────────┐ │ Admission │ 准入控制 │ Control │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ Validation │ 验证 └──────┬───────┘ │ ▼ ┌──────────────┐ │ etcd │ 存储 └──────────────┘二、RESTful API
2.1 API版本
# 核心API组/api/v1# 命名API组/apis/apps/v1 /apis/extensions/v1beta12.2 资源操作
# 创建资源POST /api/v1/namespaces/{namespace}/pods# 获取资源GET /api/v1/namespaces/{namespace}/pods/{name}# 更新资源PUT /api/v1/namespaces/{namespace}/pods/{name}# 删除资源DELETE /api/v1/namespaces/{namespace}/pods/{name}# 列表资源GET /api/v1/namespaces/{namespace}/pods2.3 使用kubectl
# kubectl是API Server的客户端kubectl get pods# 等价于curl-X GET https://api-server:6443/api/v1/namespaces/default/pods# 创建资源kubectl create -f pod.yaml# 等价于curl-X POST https://api-server:6443/api/v1/namespaces/default/pods\-H"Content-Type: application/yaml"\-d @pod.yaml三、认证(Authentication)
3.1 认证方式
1. 证书认证
# 客户端证书--client-ca-file=/etc/kubernetes/pki/ca.crt# 使用证书curl--cert client.crt --key client.key\https://api-server:6443/api/v1/pods2. Token认证
# Bearer Tokencurl-H"Authorization: Bearer <token>"\https://api-server:6443/api/v1/pods3. ServiceAccount认证
apiVersion:v1kind:ServiceAccountmetadata:name:my-sa---apiVersion:v1kind:Podspec:serviceAccountName:my-sacontainers:-name:appimage:myapp:latest3.2 认证链
API Server按顺序尝试以下认证方式:
- X509客户端证书
- Bearer Token
- ServiceAccount Token
- 匿名请求
四、授权(Authorization)
4.1 RBAC授权
Role定义:
apiVersion:rbac.authorization.k8s.io/v1kind:Rolemetadata:name:pod-readerrules:-apiGroups:[""]resources:["pods"]verbs:["get","watch","list"]RoleBinding:
apiVersion:rbac.authorization.k8s.io/v1kind:RoleBindingmetadata:name:read-podssubjects:-kind:Username:aliceapiGroup:rbac.authorization.k8s.ioroleRef:kind:Rolename:pod-readerapiGroup:rbac.authorization.k8s.io4.2 ClusterRole和ClusterRoleBinding
apiVersion:rbac.authorization.k8s.io/v1kind:ClusterRolemetadata:name:cluster-adminrules:-apiGroups:["*"]resources:["*"]verbs:["*"]