Skip to content

Latest commit

 

History

History
356 lines (335 loc) · 10.8 KB

04.kube-apiserver.md

File metadata and controls

356 lines (335 loc) · 10.8 KB

部署 kube-apiserver 组件


下载最新版kubernetes安装包

1.1 下载安装包

$ cd
$ wget https://dl.k8s.io/v1.13.1/kubernetes-server-linux-amd64.tar.gz
$ tar zxf kubernetes-server-linux-amd64.tar.gz

1.2 拷贝master端所需文件

$ export NODE_IPS=(192.168.133.128 192.168.133.129 192.168.133.130)
$ for node_ip in ${NODE_IPS[@]};
do
  echo ">>> ${node_ip}"
  scp kubernetes/server/bin/{kubeadm,kubectl,kube-apiserver,kube-controller-manager,kube-scheduler} ${node_ip}:/usr/sbin/
done

生成 kube-apiserver 所需证书文件

2.1 创建admin证书及签名请求

创建admin配置文件
$ cd /root/pki/ssl/
$ cat > admin-csr.json <<EOF
{
  "CN": "admin",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "system:masters",
      "OU": "4Paradigm"
    }
  ]
}
EOF
生成admin证书和私钥
$ cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
  -ca-key=/etc/kubernetes/ssl/ca-key.pem \
  -config=/etc/kubernetes/ssl/ca-config.json \
  -profile=kubernetes admin-csr.json | cfssljson -bare admin
$ ls admin*
分发admin证书到master节点
$ export NODE_IPS=(192.168.133.128 192.168.133.129 192.168.133.130)
$ for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp admin* ${node_ip}:/etc/kubernetes/ssl/
    ssh root@${node_ip} "chmod 755 /etc/kubernetes/ssl/admin*.pem"
  done

2.2 创建kubeconfig文件

生产kubeconfig
$ export MASTER_VIP=192.168.133.200
$ export KUBE_APISERVER="https://${MASTER_VIP}:8443"

$ kubectl config set-cluster kubernetes \
  --certificate-authority=/etc/kubernetes/ssl/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=kubectl.kubeconfig

$ kubectl config set-credentials admin \
  --client-certificate=admin.pem \
  --client-key=admin-key.pem \
  --embed-certs=true \
  --kubeconfig=kubectl.kubeconfig

$ kubectl config set-context kubernetes \
  --cluster=kubernetes \
  --user=admin \
  --kubeconfig=kubectl.kubeconfig

$ kubectl config use-context kubernetes --kubeconfig=kubectl.kubeconfig
分发kubeconfig文件
$ export NODE_IPS=(192.168.133.128 192.168.133.129 192.168.133.130)
$ for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p ~/.kube"
    scp kubectl.kubeconfig root@${node_ip}:~/.kube/config
  done

2.3 创建apiserver证书及请求文件

创建 apiserver 证书配置文件
$ export MASTER_VIP=192.168.133.200
$ export CLUSTER_KUBERNETES_SVC_IP="10.254.0.1"

$ cat > kubernetes-csr.json <<EOF
{
  "CN": "kubernetes",
  "hosts": [
    "127.0.0.1",
    "192.168.133.128",
    "192.168.133.129",
    "192.168.133.130",
    "${MASTER_VIP}",
    "${CLUSTER_KUBERNETES_SVC_IP}",
    "kubernetes",
    "kubernetes.default",
    "kubernetes.default.svc",
    "kubernetes.default.svc.cluster",
    "kubernetes.default.svc.cluster.local"
  ],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF
生成 apiserver 证书和私钥
$ cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
  -ca-key=/etc/kubernetes/ssl/ca-key.pem \
  -config=/etc/kubernetes/ssl/ca-config.json \
  -profile=kubernetes kubernetes-csr.json | cfssljson -bare kubernetes
$ ls kubernetes*.pem
分发apiserver证书到master节点
$ export NODE_IPS=(192.168.133.128 192.168.133.129 192.168.133.130)
$ for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kubernetes* ${node_ip}:/etc/kubernetes/ssl/
    ssh root@${node_ip} "chmod 755 /etc/kubernetes/ssl/kubernetes*.pem"
  done

2.4 创建加密配置文件

$ ENCRYPTION_KEY=$(head -c 32 /dev/urandom | base64)
$ cat > /tmp/encryption-config.yaml <<EOF
kind: EncryptionConfig
apiVersion: v1
resources:
  - resources:
      - secrets
    providers:
      - aescbc:
          keys:
            - name: key1
              secret: ${ENCRYPTION_KEY}
      - identity: {}
EOF
创建 audit-polic 文件
cat > /tmp/audit-policy.yaml << EOF
apiVersion: audit.k8s.io/v1
kind: Policy
# Don't generate audit events for all requests in RequestReceived stage.
omitStages:
  - "RequestReceived"
rules:
  # Log pod changes at RequestResponse level
  - level: RequestResponse
    resources:
    - group: ""
      # Resource "pods" doesn't match requests to any subresource of pods,
      # which is consistent with the RBAC policy.
      resources: ["pods"]
      
  # Log "pods/log", "pods/status" at Metadata level
  - level: Metadata
    resources:
    - group: ""
      resources: ["pods/log", "pods/status"]
      
  # Don't log requests to a configmap called "controller-leader"
  - level: None
    resources:
    - group: ""
      resources: ["configmaps"]
      resourceNames: ["controller-leader"]
      
  # Don't log watch requests by the "system:kube-proxy" on endpoints or services.
  - level: None
    users: ["system:kube-proxy"]
    verbs: ["watch"]
    resources:
    - group: "" 
      resources: ["endpoints", "services"]
      
  # Don't log authenticated requests to certain non-resource URL paths.
  - level: None
    userGroups: ["system:authenticated"]
    nonResourceURLs:
    - "/api*" 
    - "/version"
    
  # Log the request body of configmap changes in kube-system.
  - level: Request
    resources:
    - group: "" 
    # This rule only applies to resources in the "kube-system" namespace.
    # The empty string "" can be used to select non-namespaced resources.
    namespaces: ["kube-system"]

  # Log configmap and secret changes in all other namespaces at the Metadata level.
  - level: Metadata
    resources:
    - group: "" # core API group
      resources: ["secrets", "configmaps"]
      
  # Log all other resources in core and extensions at the Request level.
  - level: Request
    resources:
    - group: "" 
    - group: "extensions" 
    
  # A catch-all rule to log all other requests at the Metadata level.
  - level: Metadata
    omitStages:
      - "RequestReceived"
EOF
将加密配置文件拷贝到master节点
$ export NODE_IPS=(192.168.133.128 192.168.133.129 192.168.133.130)
$ for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp /tmp/{encryption-config.yaml,audit-policy.yaml} root@${node_ip}:/etc/kubernetes/
  done

生成 APIserver 所需证书文件

3.1 创建 kube-apiserver 服务启动文件模板

$ export SERVICE_CIDR="10.254.0.0/16"
$ export NODE_PORT_RANGE="30000-50000"
$ export ETCD_ENDPOINTS="https://192.168.133.128:2379,https://192.168.133.129:2379,https://192.168.133.130:2379"

$ cat <<EOF > /tmp/kube-apiserver.service
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=network.target

[Service]
ExecStart=/usr/sbin/kube-apiserver \\
  --port=0 \\
  --bind-address=0.0.0.0 \\
  --authorization-mode=Node,RBAC \\
  --kubelet-https=true \\
  --enable-admission-plugins=Initializers,NamespaceLifecycle,NodeRestriction,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota \\
  --kubelet-client-certificate=/etc/kubernetes/ssl/admin.pem \\
  --kubelet-client-key=/etc/kubernetes/ssl/admin-key.pem \\
  --anonymous-auth=false \\
  --encryption-provider-config=/etc/kubernetes/encryption-config.yaml \\
  --advertise-address=##NODE_IP## \\
  --runtime-config=api/all \\
  --enable-bootstrap-token-auth \\
  --service-cluster-ip-range=${SERVICE_CIDR} \\
  --service-node-port-range=${NODE_PORT_RANGE} \\
  --tls-cert-file=/etc/kubernetes/ssl/kubernetes.pem \\
  --tls-private-key-file=/etc/kubernetes/ssl/kubernetes-key.pem \\
  --client-ca-file=/etc/kubernetes/ssl/ca.pem \\
  --service-account-key-file=/etc/kubernetes/ssl/ca-key.pem \\
  --etcd-cafile=/etc/kubernetes/ssl/ca.pem \\
  --etcd-certfile=/etc/kubernetes/ssl/kubernetes.pem \\
  --etcd-keyfile=/etc/kubernetes/ssl/kubernetes-key.pem \\
  --etcd-servers=${ETCD_ENDPOINTS} \\
  --enable-swagger-ui=true \\
  --endpoint-reconciler-type=lease \\
  --allow-privileged=true \\
  --apiserver-count=3 \\
  --audit-log-maxage=30 \\
  --audit-log-maxbackup=3 \\
  --audit-log-maxsize=100 \\
  --audit-log-path=/var/log/kube-apiserver-audit.log \\
  --audit-policy-file=/etc/kubernetes/audit-policy.yaml \\
  --event-ttl=1h \\
  --enable-aggregator-routing=true \\
  --runtime-config=batch/v2alpha1=true \\
  --v=2
Restart=on-failure
RestartSec=5
Type=notify
User=root
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

分发生成的 systemd unit 文件

$ export NODE_IPS=(192.168.133.128 192.168.133.129 192.168.133.130)
$ for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/log/kubernetes"
  	scp /tmp/kube-apiserver.service ${node_ip}:/etc/systemd/system/kube-apiserver.service
    ssh root@${node_ip} "sed -i 's/##NODE_IP##/${node_ip}/' /etc/systemd/system/kube-apiserver.service"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-apiserver && systemctl restart kube-apiserver"
  done

打印kube-apiserver写入etcd的数据

$ export ETCDCTL_API=3
$ etcdctl \
    --cacert=/etc/kubernetes/ssl/ca.pem \
    --cert=/etc/etcd/ssl/etcd.pem \
    --key=/etc/etcd/ssl/etcd-key.pem --endpoints=https://192.168.133.128:2379,https://192.168.133.128:2379,https://192.168.133.128:2379  \
    get /registry/ --prefix --keys-only

检查集群信息

$ kubectl cluster-info
Kubernetes master is running at https://192.168.133.200:8443

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
$ kubectl get all --all-namespaces
NAMESPACE   NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
default     service/kubernetes   ClusterIP   10.254.0.1   <none>        443/TCP   3m
$ kubectl get componentstatuses
NAME                 STATUS      MESSAGE                                                                                     ERROR
scheduler            Unhealthy   Get http://127.0.0.1:10251/healthz: dial tcp 127.0.0.1:10251: connect: connection refused   
controller-manager   Unhealthy   Get http://127.0.0.1:10252/healthz: dial tcp 127.0.0.1:10252: connect: connection refused   
etcd-2               Healthy     {"health": "true"}                                                                          
etcd-0               Healthy     {"health": "true"}                                                                          
etcd-1               Healthy     {"health": "true"}

授予 admin 证书访问 kubelet API 的权限

在执行 kubectl exec/run/logs 等命令时,apiserver 会转发到 kubelet。这里定义 RBAC 规则,授权 apiserver 调用 kubelet API。

$ kubectl create clusterrolebinding kube-apiserver:kubelet-apis --clusterrole=system:kubelet-api-admin --user kubernetes