diff --git a/KUBE_CERTIFICATE_UPDATE_README.md b/KUBE_CERTIFICATE_UPDATE_README.md new file mode 100644 index 0000000..732bef9 --- /dev/null +++ b/KUBE_CERTIFICATE_UPDATE_README.md @@ -0,0 +1,90 @@ +# kubeadm을 이용한 인증서 갱신 + +## Prerequisites + * kubeadm + +## Step0. 인증서 만료 확인 +* 목적 : `인증서가 만료되는 시기를 확인한다.` +* 순서 : + ```bash + kubeadm alpha certs check-expiration + ``` + ```bash + CERTIFICATE EXPIRES RESIDUAL TIME CERTIFICATE AUTHORITY EXTERNALLY MANAGED + admin.conf Nov 30, 2021 07:23 UTC 364d no + apiserver Nov 30, 2021 07:23 UTC 364d ca no + apiserver-etcd-client Nov 30, 2021 07:23 UTC 364d etcd-ca no + apiserver-kubelet-client Nov 30, 2021 07:23 UTC 364d ca no + controller-manager.conf Nov 30, 2021 07:23 UTC 364d no + etcd-healthcheck-client Nov 30, 2021 07:23 UTC 364d etcd-ca no + etcd-peer Nov 30, 2021 07:23 UTC 364d etcd-ca no + etcd-server Nov 30, 2021 07:23 UTC 364d etcd-ca no + front-proxy-client Nov 30, 2021 07:23 UTC 364d front-proxy-ca no + scheduler.conf Nov 30, 2021 07:23 UTC 364d no + + CERTIFICATE AUTHORITY EXPIRES RESIDUAL TIME EXTERNALLY MANAGED + ca Nov 21, 2030 06:29 UTC 9y no + etcd-ca Nov 21, 2030 06:29 UTC 9y no + front-proxy-ca Nov 21, 2030 06:29 UTC 9y no + ``` + +## Step1. 인증서 갱신 +* 목적 : `인증서를 수동으로 갱신한다.` +* 순서 : + * 아래 명령어는 /etc/kubernetes/pki 에 저장된 CA(또는 프론트 프록시 CA) 인증서와 키를 사용하여 갱신을 수행한다. + * kubeadm으로 생성된 클라이언트 인증서는 1년 기준이다. + ```bash + kubeadm alpha certs renew all + + + [renew] Reading configuration from the cluster... + [renew] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml' + + certificate embedded in the kubeconfig file for the admin to use and for kubeadm itself renewed + certificate for serving the Kubernetes API renewed + certificate the apiserver uses to access etcd renewed + certificate for the API server to connect to kubelet renewed + certificate embedded in the kubeconfig file for the controller manager to use renewed + certificate for liveness probes to healthcheck etcd renewed + certificate for etcd nodes to communicate with each other renewed + certificate for serving etcd renewed + certificate for the front proxy client renewed + certificate embedded in the kubeconfig file for the scheduler manager to use renewed + ``` + * kube-system pod (kube scheduler, api server, controller, etcd) 재기동 + ```bash + kubectl get pod -n kube-system -o yaml | kubectl replace --force -f- + + ex) kubectl get pod kube-apiserver-k8s-master -n kube-system -o yaml | kubectl replace --force -f- + ``` + * config 복사 + ```bash + cp -i /etc/kubernetes/admin.conf /root/.kube/config + ``` +* 비고 : + * warning : 다중화 클러스터 구성의 경우, 모든 컨트롤 플레인 노드에서 이 명령을 실행해야 한다. + * 이미 인증서가 만료된 경우 아래 가이드를 참조하여 인증서를 갱신한다. + * 기존 인증서 및 config 백업 (권장사항) + ```bash + mkdir ~/cert_temp + + cd /etc/kubernetes/pki/ + mv {apiserver.crt,apiserver-etcd-client.key,apiserver-kubelet-client.crt,front-proxy-ca.crt,front-proxy-client.crt,front-proxy-client.key,front-proxy-ca.key,apiserver-kubelet-client.key,apiserver.key,apiserver-etcd-client.crt} ~/cert_temp + + cd /etc/kubernetes/pki/etcd + mv {ca.crt,ca.key,healthcheck-client.crt,healthcheck-client.key,peer.crt,peer.key,server.crt,server.key} ~/cert_temp + + cd /etc/kubernetes/ + mv {admin.conf,controller-manager.conf,mv kubelet.conf,scheduler.conf} ~/cert_temp + ``` + * 새 인증서 생성 및 config 변경 적용 + ```bash + kubeadm init phase certs all --apiserver-advertise-address + + kubeadm init phase kubeconfig all + ``` + * reboot + * kube config 복사 + ```bash + cp -i /etc/kubernetes/admin.conf $HOME/.kube/config + ``` diff --git a/KUBE_VERSION_UPGRADE_README.md b/KUBE_VERSION_UPGRADE_README.md index 8d9129f..34f7c3c 100644 --- a/KUBE_VERSION_UPGRADE_README.md +++ b/KUBE_VERSION_UPGRADE_README.md @@ -343,7 +343,7 @@ sudo vi /var/lib/kubelet/kubeadm-flags.env에 옵션 변경 - 기존 (docker) : KUBELET_KUBEADM_ARGS="--cgroup-driver=cgroupfs --network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.1 + 기존 (docker) : KUBELET_KUBEADM_ARGS="--cgroup-driver=cgroupfs --network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.1" 변경 (cri-o) : KUBELET_KUBEADM_ARGS="--container-runtime=remote --cgroup-driver=systemd --container-runtime-endpoint=/var/run/crio/crio.sock" systemctl restart kubelet diff --git a/LBNODE_README.md b/LBNODE_README.md new file mode 100644 index 0000000..2c5b102 --- /dev/null +++ b/LBNODE_README.md @@ -0,0 +1,155 @@ +# K8S Master 클러스터의 LBNode 설치 가이드(HAProxy + Keepalived) +* 본 가이드는 별도의 LBNode를 갖는 K8S 다중화 클러스터 구축을 위해 작성되었음. +* 구축하려는 LBNode에 해당 파일들이 같은 디렉터리 내에 존재해야 함. + +## 구성 요소 및 버전 +* Keepalived v1.3.5 # LBNode에 설치 +* HA-Proxy v1.5.18 # LBNode에 설치 + +## Install Steps +0. 변수 설정 +1. HAProxy + Keepalived 설치 +2. 설치한 서비스 재시작 +3. K8S 클러스터 구축 + +## Step 0. 변수 설정 +* 목적 : `LB Node 구축을 위한 변수 설정` +* 순서 : + * Keepalived 와 HAProxy를 설치 및 동작시키기 위한 변수를 설정한다. + * 클러스터 구성에 사용할 각 Master Node의 IP, VIP, LBNode에 대한 정보를 입력한다. + ```bash + export MASTER1NAME=test # 클러스터로 구성할 Master Node의 host명을 각각 입력. + export MASTER2NAME=worker + export MASTER3NAME=worker2 + + export MASTER1IP=192.168.56.222 # Master Node의 IP를 각각 입력. + export MASTER2IP=192.168.56.223 + export MASTER3IP=192.168.56.224 + + export LB1=192.168.56.250 # 현재 LB Node의 IP를 입력. + export LB2=192.168.56.249 # 다른 LB Node의 IP를 입력. + + export VIP=192.168.56.240 # K8S Master Join시VIP로 사용할 IP를 입력. + ``` + +## Step.1 HAProxy + Keepalived 설치 +* 목적 : `설치 스크립트를 실행하여 HAProxy와 Keepalived를 LBNode에 설치` +* 순서 : + * 설치 스크립트에 실행 권한을 주고, 실행한다. + ```bash + chmod +x lb_set_script.sh + ./lb_set_script.sh + ``` + +## Step.2 설치한 서비스 재시작 +* 목적 : `HAProxy와 Keepalived 재시작` +* 순서 : + * 각 서비스의 설정파일에 Step0 에서 입력한 값들이 올바르게 설정되었는지 확인한다. + ```bash + vi /etc/keepalived/keepalived.conf + vi /etc/haproxy/haproxy.cfg + ``` + + * Keepalived 설정파일의 세부내용을 확인/수정한다. + * state 필드는 MASTER or BACKUP을 반드시 수정하며, priority 또한 수정한다. + * interface도 수정해줘야한다. + ```bash + global_defs { + script_user root root + enable_script_security off + } + + vrrp_script chk_haproxy { + script "/usr/sbin/pidof haproxy" + interval 2 + weight 2 + } + + vrrp_instance VI_1 { + state MASTER # MASTER는 메인 LB, 백업 LB는 BACKUP 으로 설정 + interface enp0s8 # 사용할 interface + virtual_router_id 51 + priority 100 # MASTER의 우선순위가 적어도 1이상 높아야 함 + advert_int 1 + nopreempt + authentication { # 인증에 사용될 password(동일하게 맞춰주기만 하면 됨) + auth_type PASS + auth_pass 1111 + } + + unicast_src_ip LB1 # LB 서버 local ip + + unicast_peer { + LB2 # 다른 LB 서버 local ip + } + + virtual_ipaddress { + VIP # 클러스터 구성에 사용될 VIP! + } + + notify_master "/bin/sh /etc/keepalived/notify_action.sh MASTER" + notify_backup "/bin/sh /etc/keepalived/notify_action.sh BACKUP" + notify_fault "/bin/sh /etc/keepalived/notify_action.sh FAULT" + notify_stop "/bin/sh /etc/keepalived/notify_action.sh STOP" + + track_script { + chk_haproxy + } + + track_interface { + enp0s8 # 사용할 interface + } + } + ``` + + * HA Proxy 설정파일의 세부내용을 확인/수정한다. + ```bash + global + log 127.0.0.1 local2 + maxconn 2000 + uid 0 + gid 0 + daemon # background process + + defaults + log global # global 설정 사용 + mode tcp # SSL 통신을 위해서는 TCP모드로 (http모드는 SSL 안됨) + option tcplog + option dontlognull # 데이터가 전송되지 않은 연결 로깅 제외 + retries 3 # 연결요청 재시도 횟수 + maxconn 2000 #option redispatch + timeout connect 10s + timeout client 1m + timeout server 1m + + frontend k8s-api + bind 0.0.0.0:16443 + default_backend k8s-api + + backend k8s-api + option tcp-check + balance roundrobin + server MASTER1NAME MASTER1IP check # Master 다중화 서버들 정보 기재 + server MASTER2NAME MASTER2IP check + server MASTER3NAME MASTER3IP check + ``` + + * 각 서비스를 활성화시켜주며 재시작하고, 동작을 확인한다. + ```bash + systemctl enable haproxy + systemctl enable keepalived + + systemctl daemon-reload + + systemctl restart haproxy + systemctl restart keepalived + + systemctl status haproxy + systemctl status keepalived + ``` + +## Step.3 K8S cluster 구축 +* 목적 : `LB Node 설정을 완료한 이후, K8S 클러스터 구축을 계속한다` +* 순서 : + * 아래의 GUIDE에서, 3-1번(keepalived 설치)을 제외하고 클러스터 구축을 수행한다. + * [K8S MASTER INSTALL GUIDE](https://github.com/tmax-cloud/install-k8s#k8s-cluster-%EA%B5%AC%EC%B6%95-%EA%B0%80%EC%9D%B4%EB%93%9C) diff --git a/README.md b/README.md index 7a77eaf..34ac917 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,5 @@ -### 문의 -* 폐쇄망 구축 관련된 옵션들은 전부 폐쇄망 구축 가이드로 이전 요청(ex. crio 설치 과정) -* Master/Worker의 문서 통합 요청 -* 다중화 Cluster의 문서 통합 요청 -* Docker registry 설정이 필요한지? (3-2), Image registry는 docker registry를 계속 사용할 것인지? -* root directory에는 README.md, manifest가 필수 존재 (manifest directory 하위에 모든 설치 파일이 존재) -* README.md 의 항목은 '구성 요소 및 버전', '폐쇄망 구축 가이드', '설치 가이드', '삭제 가이드' 가 필수 요소 - - -# K8s Cluster 구축 가이드 -※ [듀얼 스택 클러스터 구축을 위한 k8s-master 설치 가이드](/README_dualstack.md) - ## 구성 요소 및 버전 -* cri-o (v1.17.4) +* cri-o (v1.17.4) or docker-ce(v18.09.7) * kubeadm, kubelet, kubectl (v1.17.6) * k8s.gcr.io/kube-apiserver:v1.17.6 * k8s.gcr.io/kube-proxy:v1.17.6 @@ -22,7 +10,6 @@ * k8s.gcr.io/coredns:1.6.5 ## 폐쇄망 구축 가이드 - 1. **폐쇄망에서 설치하는 경우** 아래 가이드를 참고 하여 image registry를 먼저 구축한다. * https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/Image_Registry 2. 사용하는 image repository에 k8s 설치 시 필요한 이미지를 push한다. @@ -30,6 +17,8 @@ ```bash $ mkdir -p ~/k8s-install $ cd ~/k8s-install + $ export REGISTRY={ImageRegistryIP:Port} + ex) $ export REGISTRY=172.22.5.2:5000 ``` * 외부 네트워크 통신이 가능한 환경에서 필요한 이미지를 다운받는다. ```bash @@ -90,17 +79,22 @@ ![image](figure/check.PNG) * 비고 : * 위 내용은 2개이상의 마스터 구축시 마스터 1개에서만 진행한다. - + ## 설치 가이드 - -0. [환경 설정](/README.md#step0-%ED%99%98%EA%B2%BD-%EC%84%A4%EC%A0%95) -1. [cri-o 설치](/README.md#step-1-cri-o-%EC%84%A4%EC%B9%98) -2. [kubeadm, kubelet, kubectl 설치](/README.md#step-2-kubeadm-kubelet-kubectl-%EC%84%A4%EC%B9%98) -3. [kubernetes cluster 구성](/README.md#step-3-kubernetes-cluster-%EA%B5%AC%EC%84%B1) +0. [(Master/Worker 공통) 환경 설정](/README.md#step0-%ED%99%98%EA%B2%BD-%EC%84%A4%EC%A0%95) +1. [(Master/Worker 공통) runtime 설치 - cri-o 설치](/README.md#step-1-cri-o-%EC%84%A4%EC%B9%98) +1-1. [docker-ce 설치](/README.md#step-1-cri-o-%EC%84%A4%EC%B9%98) +2. [(Master/Worker 공통) kubeadm, kubelet, kubectl 설치](/README.md#step-2-kubeadm-kubelet-kubectl-%EC%84%A4%EC%B9%98) +3. [(Master) kubernetes cluster 구성](/README.md#step-3-kubernetes-cluster-%EA%B5%AC%EC%84%B1) 3-1. [kubernetes cluster 구성(master 다중화)](/README.md#step-3-1-kubernetes-cluster-%EB%8B%A4%EC%A4%91%ED%99%94-%EA%B5%AC%EC%84%B1%EC%9D%84-%EC%9C%84%ED%95%9C-keepalived-%EC%84%A4%EC%B9%98) -4. [kubernetes cluster join](/README.md#step-4-cluster-join-worker) +4. [(Worker) kubernetes cluster join](/README.md#step-4-cluster-join-worker) -## Step0. 환경 설정 +## 삭제 가이드 +0. [(Master/Worker 공통) kubernetes cluster reset](https://github.com/jinho0928/install-k8s#step-1-cluster-reset-masterworker-%EA%B3%B5%ED%86%B5) +1. [(Master/Worker 공통) 패키지 삭제](https://github.com/jinho0928/install-k8s/blob/main/README.md#step-2-%EC%84%A4%EC%B9%98-%ED%8C%A8%ED%82%A4%EC%A7%80-%EC%82%AD%EC%A0%9C-masterworker-%EA%B3%B5%ED%86%B5) + +## 설치 가이드 +## Step0. 환경 설정 (Master/Worker 공통) * 목적 : `k8s 설치 진행을 위한 os 환경 설정` * 순서 : * os hostname을 설정한다. @@ -136,7 +130,7 @@ sudo setenforce 0 sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config ``` - * crio 사용 전 환경 설정 + * (cri-o) 사용 전 환경 설정 ```bash sudo modprobe overlay sudo modprobe br_netfilter @@ -149,12 +143,24 @@ sudo sysctl --system ``` -## Step 1. cri-o 설치 (Master/Worker 공통) -* 목적 : `k8s container runtime 설치` + * (docker) 사용 전 환경 설정 + ```bash + sudo cat << "EOF" | sudo tee -a /etc/sysctl.d/k8s.conf + net.bridge.bridge-nf-call-iptables = 1 + net.ipv4.ip_forward = 1 + net.bridge.bridge-nf-call-ip6tables = 1 + EOF + + sudo sysctl --system + ``` + * xfs filesystem을 사용하는 경우, 'xfs_info /' 커맨드가 ftype=1이 출력되는지 확인한다. + +## Step 1. cri-o 설치 및 설정 (Master/Worker 공통) +* 목적 : `k8s container cri-o runtime 설치` * 순서 : - * cri-o를 설치한다. + * cri-o를 설치한다. * (폐쇄망) 아래 주소를 참조하여 패키지 레포를 등록 후 crio를 설치한다. - * https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/Package#step-1-local-repository-%EA%B5%AC%EC%B6%95 + * https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/Package#step-1-local-repository-%EA%B5%AC%EC%B6%95 ```bash sudo yum -y install cri-o sudo systemctl enable crio @@ -182,21 +188,18 @@ sudo rm -rf /etc/cni/net.d/100-crio-bridge.conf sudo rm -rf /etc/cni/net.d/200-loopback.conf ``` - * 폐쇄망 환경에서 private registry 접근을 위해 crio.conf 내용을 수정한다. - * insecure_registry, registries, plugin_dirs 내용을 수정한다. - * sudo vi /etc/crio/crio.conf - * registries = ["{registry}:{port}" , "docker.io"] - * insecure_registries = ["{registry}:{port}"] - * plugin_dirs : "/opt/cni/bin" 추가 - * (폐쇄망) pause_image : "k8s.gcr.io/pause:3.1" 을 "{registry}:{port}/k8s.gcr.io/pause:3.1" 로 변경 - ![image](figure/crio_config.PNG) + * crio.conf 내용을 수정한다. ( sudo vi /etc/crio/crio.conf ) + * plugin_dirs : "/opt/cni/bin" 추가 + * (폐쇄망) insecure_registries = ["{registry}:{port}"] + * (폐쇄망) pause_image : "k8s.gcr.io/pause:3.1" 을 "{registry}:{port}/k8s.gcr.io/pause:3.1" 로 변경 + ![image](figure/crio_config.PNG) * pid cgroup의 max pid limit 설정이 필요한 경우 pids_limit 개수를 수정한다. * default : pids_limit = 1024 * 시스템의 제한값인 `/proc/sys/kernel/pid_max`의 값 이하로 설정한다. ```bash pids_limit = 32768 ``` - * registries.conf 내용을 수정한다. + * private image registry를 사용할 경우 registries.conf 내용을 수정한다. * sudo vi /etc/containers/registries.conf ```bash unqualified-search-registries = ['registry.fedoraproject.org', 'registry.access.redhat.com', 'registry.centos.org', 'docker.io', '{registry}:{port}'] @@ -205,7 +208,45 @@ * crio를 재시작 한다. ```bash sudo systemctl restart crio - ``` + ``` + +## Step 1-1. docker-ce 설치 및 설정 (Master/Worker 공통) +* 목적 : `k8s container docker runtime 설치` +* 생성 순서 : + * docker-ce를 설치한다. (image registry 구축 시에 docker를 이미 설치하였고 daemon.json 내용이 같다면 step1-1의 과정은 생략한다.) + ```bash + sudo yum install -y docker-ce + sudo systemctl start docker + sudo systemctl enable docker + ``` + * 폐쇄망 환경에서 private registry 접근을 위해 daemon.json 내용을 수정한다. + * sudo vi /etc/docker/daemon.json + ```bash + { + "exec-opts": ["native.cgroupdriver=systemd"], + "log-driver": "json-file", + "log-opts": { "max-size": "100m" }, + "storage-driver": "overlay2", + "insecure-registries": ["{registry}:{port}"] + } + ``` + * docker를 재실행하고 status를 확인한다. + ```bash + sudo systemctl restart docker + sudo systemctl status docker + ``` +* 비고 : + * private image registry를 사용할 경우 registries.conf 내용을 수정한다. + * sudo vi /etc/containers/registries.conf + ```bash + unqualified-search-registries = ['registry.fedoraproject.org', 'registry.access.redhat.com', 'registry.centos.org', 'docker.io', '{registry}:{port}'] + ex) unqualified-search-registries = ['registry.fedoraproject.org', 'registry.access.redhat.com', 'registry.centos.org', 'docker.io', '172.22.5.2:5000'] + ``` + * docker를 재시작 한다. + ```bash + sudo systemctl restart docker + ``` + ## Step 2. kubeadm, kubelet, kubectl 설치 (Master/Worker 공통) * 목적 : `Kubernetes 구성을 위한 kubeadm, kubelet, kubectl 설치한다.` * 순서: @@ -249,12 +290,12 @@ --- apiVersion: kubeadm.k8s.io/v1beta2 kind: ClusterConfiguration - kubernetesVersion: v1.17.6 + kubernetesVersion: {k8s version} controlPlaneEndpoint: {endpoint IP}:6443 imageRepository: {registry}/k8s.gcr.io networking: - serviceSubnet: 10.96.0.0/16 - podSubnet: {POD_IP_POOL}/16 + serviceSubnet: {SERVICE_IP_POOL}/{CIDR} + podSubnet: {POD_IP_POOL}/{CIDR} --- apiVersion: kubelet.config.k8s.io/v1beta1 kind: KubeletConfiguration @@ -265,19 +306,19 @@ * 해당 master 노드의 IP * controlPlaneEndpoint : endpoint IP ( master IP or virtual IP) , port는 반드시 6443으로 설정 * 1개의 마스터 : master IP , 2개 이상의 마스터 구축시 : virtual IP - * serviceSubnet : "${SERVICE_IP_POOL}/${CIDR}" - * podSubnet : "${POD_IP_POOL}/${CIDR}" - * imageRepository : "${registry} / docker hub name" + * serviceSubnet : ${SERVICE_IP_POOL}/${CIDR} + * podSubnet : ${POD_IP_POOL}/${CIDR} + * imageRepository : ${registry}/docker_hub_name * cgroupDriver: cgroup driver systemd 변경 - - * kubeadm init (2개 이상 마스터 구축시에는 아래 가이드 참조) + + * kubeadm init (2개 이상 마스터 구축시에는 아래 가이드 참조) ```bash sudo kubeadm init --config=kubeadm-config.yaml ``` + ![image](figure/kubeinit.PNG) * 마스터 다중화 진행시 아래 마스터 다중화 가이드로 설치를 진행한다. - * [마스터 다중화 가이드](https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/K8S_Master#step-3-1-kubernetes-cluster-%EB%8B%A4%EC%A4%91%ED%99%94-%EA%B5%AC%EC%84%B1%EC%9D%84-%EC%9C%84%ED%95%9C-keepalived-%EC%84%A4%EC%B9%98) - - ![image](figure/kubeinit.PNG) + * [마스터 다중화 가이드](https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/K8S_Master#step-3-1-kubernetes-cluster-%EB%8B%A4%EC%A4%91%ED%99%94-%EA%B5%AC%EC%84%B1%EC%9D%84-%EC%9C%84%ED%95%9C-keepalived-%EC%84%A4%EC%B9%98) + * 듀얼 스택 클러스터 구축 시에는 아래의 [비고] yaml을 참조하여 진행한다. * kubernetes config ```bash mkdir -p $HOME/.kube @@ -299,16 +340,56 @@ ```bash kubectl taint node [master hostname] node-role.kubernetes.io/master:NoSchedule- ex) kubectl taint node k8s- node-role.kubernetes.io/master:NoSchedule- - ``` - -## Step 3-1. kubernetes cluster 다중화 구성을 위한 Keepalived 설치 + ``` + * 듀얼 스택 클러스터 구축 시에는 아래의 kubeadm-config.yaml을 참조한다. + * vi kubeadm-config.yaml + ```bash + apiVersion: kubeadm.k8s.io/v1beta2 + kind: InitConfiguration + localAPIEndpoint: + advertiseAddress: {api server IP} + bindPort: 6443 + nodeRegistration: + criSocket: /var/run/crio/crio.sock + --- + apiVersion: kubeadm.k8s.io/v1beta2 + kind: ClusterConfiguration + kubernetesVersion: {k8s version} + controlPlaneEndpoint: {endpoint IP}:6443 + imageRepository: {registry}/k8s.gcr.io + networking: + serviceSubnet: ${SERVICE_IPV4_POOL}/${CIDR},${SERVICE_IPV6_POOL}/${CIDR} + podSubnet: ${POD_IPV4_POOL}/${CIDR},${POD_IPV6_POOL}/${CIDR} + featureGates: + IPv6DualStack: true + --- + apiVersion: kubelet.config.k8s.io/v1beta1 + kind: KubeletConfiguration + cgroupDriver: systemd + --- + apiVersion: kubeproxy.config.k8s.io/v1alpha1 + kind: KubeProxyConfiguration + mode: ipvs + ``` + * kubernetesVersion : kubernetes version + * advertiseAddress : API server IP ( master IP ) + * 해당 master 노드의 IP + * controlPlaneEndpoint : endpoint IP ( master IP or virtual IP) , port는 반드시 6443으로 설정 + * 1개의 마스터 : master IP , 2개 이상의 마스터 구축시 : virtual IP + * serviceSubnet : ${SERVICE_IPV4_POOL}/${CIDR},${SERVICE_IPV6_POOL}/${CIDR} + * podSubnet : ${POD_IPV4_POOL}/${CIDR},${POD_IPV6_POOL}/${CIDR} + * imageRepository : ${registry}/docker_hub_name + * IPv6DualStack: true, dual stack 기능이 베타 버전이라서 기본값으로는 비활성화이기 때문에 활성화 시키는 세팅(추후 기본으로 활성화 되면 빠져야 함) + * cgroupDriver: cgroup driver systemd 변경 + * mode: ipvs, dual stack 기능은 kube-proxy ipvs 모드에서만 동작 + +## Step 3-1. kubernetes cluster 다중화 구성을 위한 Keepalived 설치 (Master) * 목적 : `K8S cluster의 Master 다중화 구성을 위한 Keepalived를 설치 및 설정한다` * 순서 : * Keepalived 설치 ```bash sudo yum install -y keepalived ``` - * Keepalived 설정 ```bash sudo vi /etc/keepalived/keepalived.conf @@ -344,41 +425,17 @@ sudo systemctl restart keepalived sudo systemctl enable keepalived sudo systemctl status keepalived - ``` * network interface 확인 ```bash ip a ``` + * 설정한 VIP 확인 가능, 여러 마스터 중 하나만 보임. + * inet {VIP}/32 scope global eno1 + ![image](figure/ipa.PNG) - * 설정한 VIP 확인 가능, 여러 마스터 중 하나만 보임. - * inet {VIP}/32 scope global eno1 - ![image](figure/ipa.PNG) - -## Step 3-2. docker 설치 및 설정 -* 목적 : `구성한 docker registry에 접근을 위해 docker를 설치한다.` -* 생성 순서 : - * 다른 구성하는 마스터에 docker를 설치한다. - ```bash - $ sudo yum install -y docker-ce - $ sudo systemctl start docker - $ sudo systemctl enable docker - ``` - * docker daemon에 insecure-registries를 등록한다. - * sudo vi /etc/docker/daemon.json - ```bash - { - "insecure-registries": ["{IP}:5000"] - } - ``` - * docker를 재실행하고 status를 확인한다. - ```bash - $ sudo systemctl restart docker - $ sudo systemctl status docker - ``` - -## Step 3-3. kubernetes cluster 다중화 구성 설정 +## Step 3-2. kubernetes cluster 다중화 구성 설정 * 목적 : `K8S cluster의 Master 다중화를 구성한다` * 순서 : * kubeadm-config.yaml 파일로 kubeadm 명령어 실행한다. @@ -396,7 +453,7 @@ * (1)처럼 Master 다중구성을 위한 hash 값을 포함한 kubeadm join 명령어가 출력되므로 해당 명령어를 복사하여 다중구성에 포함시킬 다른 Master에서 실행 * (2)처럼 Worker의 join을 위한 명령어도 출력되므로 Worker 노드 join시 사용, crio 사용시 --cri-socket 옵션 추가 ```bash - sudo kubeadm join 172.22.5.2:6443 --token 2cks7n.yvojnnnq1lyz1qud \ --discovery-token-ca-cert-hash sha256:efba18bb4862cbcb54fb643a1b7f91c25e08cfc1640e5a6fffa6de83e4c76f07 \ --control-plane --certificate-key f822617fcbfde09dff35c10e388bc881904b5b6c4da28f3ea8891db2d0bd3a62 --cri-socket=/var/run/crio/crio.sock + kubeadm join 172.22.5.2:6443 --token 2cks7n.yvojnnnq1lyz1qud \ --discovery-token-ca-cert-hash sha256:efba18bb4862cbcb54fb643a1b7f91c25e08cfc1640e5a6fffa6de83e4c76f07 \ --control-plane --certificate-key f822617fcbfde09dff35c10e388bc881904b5b6c4da28f3ea8891db2d0bd3a62 --cri-socket=/var/run/crio/crio.sock ``` * kubernetes config ```bash @@ -404,21 +461,54 @@ sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config ``` +* 비고 : + * join시에 apiserver ip 변경이 필요할 경우 --apiserver-advertise-address 옵션을 추가한다. + ```bash + kubeadm join 172.22.5.2:6443 --token 2cks7n.yvojnnnq1lyz1qud \ --discovery-token-ca-cert-hash sha256:efba18bb4862cbcb54fb643a1b7f91c25e08cfc1640e5a6fffa6de83e4c76f07 \ --control-plane --certificate-key f822617fcbfde09dff35c10e388bc881904b5b6c4da28f3ea8891db2d0bd3a62 --cri-socket=/var/run/crio/crio.sock --apiserver-advertise-address=172.22.4.3 + ``` + ## Step 4. Cluster join (Worker) * 목적 : `kubernetes cluster에 join한다.` * 순서 : * kubernetes master 구축시 생성된 join token을 worker node에서 실행한다. * kubeadm join - * --cri-socket=/var/run/crio/crio.sock 옵션을 token 뒤에 추가하여 실행한다. - ```bash - kubeadm join 172.22.5.2:6443 --token r5ks9p.q0ifuz5pcphqvc14 \ --discovery-token-ca-cert-hash sha256:90751da5966ad69a49f2454c20a7b97cdca7f125b8980cf25250a6ee6c804d88 --cri-socket=/var/run/crio/crio.sock - ``` + * (cri-o) join token에 --cri-socket=/var/run/crio/crio.sock 옵션을 추가하여 실행한다. + ```bash + kubeadm join 172.22.5.2:6443 --token r5ks9p.q0ifuz5pcphqvc14 \ --discovery-token-ca-cert-hash sha256:90751da5966ad69a49f2454c20a7b97cdca7f125b8980cf25250a6ee6c804d88 --cri-socket=/var/run/crio/crio.sock + ``` + * (docker) join token을 그대로 실행한다. + ```bash + kubeadm join 172.22.5.2:6443 --token r5ks9p.q0ifuz5pcphqvc14 \ --discovery-token-ca-cert-hash sha256:90751da5966ad69a49f2454c20a7b97cdca7f125b8980cf25250a6ee6c804d88 + ``` ![image](figure/noding.PNG) * 비고 : * kubeadm join command를 저장해놓지 못한 경우, master node에서 아래 명령어를 통해 token 재생성이 가능하다. ```bash kubeadm token create --print-join-command ``` - + ## 삭제 가이드 +## Step 1. Cluster reset (Master/Worker 공통) +* 목적 : `kubernetes cluster를 reset한다.` +* 순서 : + * kubeadm reset + * (cri-o) --cri-socket=/var/run/crio/crio.sock 옵션을 추가하여 kubeadm reset을 실행한다. + ```bash + kubeadm reset --cri-socket=/var/run/crio/crio.sock + ``` + * (docker) kubeadm reset을 실행한다. + ```bash + kubeadm reset + ``` +## Step 2. 설치 패키지 삭제 (Master/Worker 공통) +* 목적 : `kubernetes에 필요한 패키지들을 삭제한다` +* 순서 : + * 설치했던 패키지들을 삭제 한다. + ```bash + sudo yum remove -y kubeadm-1.17.6-0 kubelet-1.17.6-0 kubectl-1.17.6-0 + + sudo yum remove -y crio or sudo yum remove -y docker-ce + + sudo yum remove -y keepalived + ``` diff --git a/README_dualstack.md b/README_dualstack.md deleted file mode 100644 index 19c8442..0000000 --- a/README_dualstack.md +++ /dev/null @@ -1,402 +0,0 @@ - -# 다중화 k8s-master 설치 가이드 - -## 구성 요소 및 버전 -* cri-o (v1.17.4) -* kubeadm, kubelet, kubectl (v1.17.6) -* k8s.gcr.io/kube-apiserver:v1.17.6 -* k8s.gcr.io/kube-proxy:v1.17.6 -* k8s.gcr.io/kube-scheduler:v1.17.6 -* k8s.gcr.io/kube-controller-manager:v1.17.6 -* k8s.gcr.io/etcd:3.4.3-0 -* k8s.gcr.io/pause:3.1 -* k8s.gcr.io/coredns:1.6.5 - -## 폐쇄망 구축 가이드 - -1. **폐쇄망에서 설치하는 경우** 아래 가이드를 참고 하여 image registry를 먼저 구축한다. - * https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/Image_Registry -2. 사용하는 image repository에 k8s 설치 시 필요한 이미지를 push한다. - * 작업 디렉토리 생성 및 환경 설정 - ```bash - $ mkdir -p ~/k8s-install - $ cd ~/k8s-install - ``` - * 외부 네트워크 통신이 가능한 환경에서 필요한 이미지를 다운받는다. - ```bash - $ sudo docker pull k8s.gcr.io/kube-proxy:v1.17.6 - $ sudo docker pull k8s.gcr.io/kube-apiserver:v1.17.6 - $ sudo docker pull k8s.gcr.io/kube-controller-manager:v1.17.6 - $ sudo docker pull k8s.gcr.io/kube-scheduler:v1.17.6 - $ sudo docker pull k8s.gcr.io/etcd:3.4.3-0 - $ sudo docker pull k8s.gcr.io/coredns:1.6.5 - $ sudo docker pull k8s.gcr.io/pause:3.1 - ``` - ![image](figure/dockerimages.PNG) - * docker image를 tar로 저장한다. - ```bash - $ sudo docker save -o kube-proxy.tar k8s.gcr.io/kube-proxy:v1.17.6 - $ sudo docker save -o kube-controller-manager.tar k8s.gcr.io/kube-controller-manager:v1.17.6 - $ sudo docker save -o etcd.tar k8s.gcr.io/etcd:3.4.3-0 - $ sudo docker save -o coredns.tar k8s.gcr.io/coredns:1.6.5 - $ sudo docker save -o kube-scheduler.tar k8s.gcr.io/kube-scheduler:v1.17.6 - $ sudo docker save -o kube-apiserver.tar k8s.gcr.io/kube-apiserver:v1.17.6 - $ sudo docker save -o pause.tar k8s.gcr.io/pause:3.1 - ``` - ![image](figure/dockersave.PNG) -3. 위의 과정에서 생성한 tar 파일들을 폐쇄망 환경으로 이동시킨 뒤 사용하려는 registry에 이미지를 push한다. - ```bash - $ sudo docker load -i kube-apiserver.tar - $ sudo docker load -i kube-scheduler.tar - $ sudo docker load -i kube-controller-manager.tar - $ sudo docker load -i kube-proxy.tar - $ sudo docker load -i etcd.tar - $ sudo docker load -i coredns.tar - $ sudo docker load -i pause.tar - ``` - ![image](figure/dockerload.PNG) - ```bash - $ sudo docker tag k8s.gcr.io/kube-apiserver:v1.17.6 ${REGISTRY}/k8s.gcr.io/kube-apiserver:v1.17.6 - $ sudo docker tag k8s.gcr.io/kube-proxy:v1.17.6 ${REGISTRY}/k8s.gcr.io/kube-proxy:v1.17.6 - $ sudo docker tag k8s.gcr.io/kube-controller-manager:v1.17.6 ${REGISTRY}/k8s.gcr.io/kube-controller-manager:v1.17.6 - $ sudo docker tag k8s.gcr.io/etcd:3.4.3-0 ${REGISTRY}/k8s.gcr.io/etcd:3.4.3-0 - $ sudo docker tag k8s.gcr.io/coredns:1.6.5 ${REGISTRY}/k8s.gcr.io/coredns:1.6.5 - $ sudo docker tag k8s.gcr.io/kube-scheduler:v1.17.6 ${REGISTRY}/k8s.gcr.io/kube-scheduler:v1.17.6 - $ sudo docker tag k8s.gcr.io/pause:3.1 ${REGISTRY}/k8s.gcr.io/pause:3.1 - ``` - ![image](figure/tag.PNG) - ```bash - $ sudo docker push ${REGISTRY}/k8s.gcr.io/kube-apiserver:v1.17.6 - $ sudo docker push ${REGISTRY}/k8s.gcr.io/kube-proxy:v1.17.6 - $ sudo docker push ${REGISTRY}/k8s.gcr.io/kube-controller-manager:v1.17.6 - $ sudo docker push ${REGISTRY}/k8s.gcr.io/etcd:3.4.3-0 - $ sudo docker push ${REGISTRY}/k8s.gcr.io/coredns:1.6.5 - $ sudo docker push ${REGISTRY}/k8s.gcr.io/kube-scheduler:v1.17.6 - $ sudo docker push ${REGISTRY}/k8s.gcr.io/pause:3.1 - ``` - ![image](figure/push.PNG) - ```bash - $ curl ${REGISTRY}/v2/_catalog - ``` - ![image](figure/check.PNG) -* 비고 : - * 위 내용은 2개이상의 마스터 구축시 마스터 1개에서만 진행한다. - -## 설치 가이드 - -0. [환경 설정](/README_dualstack.md#step0-%ED%99%98%EA%B2%BD-%EC%84%A4%EC%A0%95) -1. [cri-o 설치](/README_dualstack.md#step-1-cri-o-%EC%84%A4%EC%B9%98) -2. [kubeadm, kubelet, kubectl 설치](/README_dualstack.md#step-2-kubeadm-kubelet-kubectl-%EC%84%A4%EC%B9%98) -3. [kubernetes cluster 구성](/README_dualstack.md#step-3-kubernetes-cluster-%EA%B5%AC%EC%84%B1) -3-1. [kubernetes cluster 구성(master 다중화)](/README_dualstack.md#step-3-1-kubernetes-cluster-%EB%8B%A4%EC%A4%91%ED%99%94-%EA%B5%AC%EC%84%B1%EC%9D%84-%EC%9C%84%ED%95%9C-keepalived-%EC%84%A4%EC%B9%98) - -## Step0. 환경 설정 -* 목적 : `k8s 설치 진행을 위한 os 환경 설정` -* 순서 : - * os hostname을 설정한다. - ```bash - sudo hostnamectl set-hostname k8s-master - ``` - * hostname과 ip를 등록한다. - * sudo vi /etc/hosts - ```bash - 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 - ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 - - 172.22.5.2 k8s-master - ``` - * 방화벽(firewall)을 해제한다. - ```bash - sudo systemctl stop firewalld - sudo systemctl disable firewalld - ``` - * 스왑 메모리를 비활성화 한다. - ```bash - sudo swapoff -a - ``` - * 스왑 메모리 비활성화 영구설정 - * sudo vi /etc/fstab - ```bash - swap 관련 부분 주석처리 - # /dev/mapper/centos-swap swap swap defaults 0 - ``` - ![image](figure/fstab.PNG) - * SELinux 설정을 해제한다. - ```bash - sudo setenforce 0 - sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config - ``` - * crio 사용 전 환경 설정 - ```bash - sudo modprobe overlay - sudo modprobe br_netfilter - - sudo cat << "EOF" | sudo tee -a /etc/sysctl.d/99-kubernetes-cri.conf - net.bridge.bridge-nf-call-iptables = 1 - net.ipv4.ip_forward = 1 - net.bridge.bridge-nf-call-ip6tables = 1 - EOF - - sudo sysctl --system - ``` -## Step 1. cri-o 설치 -* 목적 : `k8s container runtime 설치` -* 순서 : - * cri-o를 설치한다. - * (폐쇄망) 아래 주소를 참조하여 패키지 레포를 등록 후 crio를 설치한다. - * https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/Package#step-1-local-repository-%EA%B5%AC%EC%B6%95 - ```bash - sudo yum -y install cri-o - sudo systemctl enable crio - sudo systemctl start crio - ``` - * (외부망) crio 버전 지정 및 레포를 등록 후 crio를 설치한다. - ```bash - VERSION=1.17 - sudo curl -L -o /etc/yum.repos.d/devel:kubic:libcontainers:stable.repo https://download.opensuse.org/repositories/devel:kubic:libcontainers:stable/CentOS_7/devel:kubic:libcontainers:stable.repo - sudo curl -L -o /etc/yum.repos.d/devel:kubic:libcontainers:stable:cri-o:${VERSION}.repo https://download.opensuse.org/repositories/devel:kubic:libcontainers:stable:cri-o:${VERSION}/CentOS_7/devel:kubic:libcontainers:stable:cri-o:${VERSION}.repo - - sudo yum -y install cri-o - sudo systemctl enable crio - sudo systemctl start crio - ``` - * cri-o 설치를 확인한다. - ```bash - sudo systemctl status crio - rpm -qi cri-o - ``` - ![image](figure/rpm.PNG) -* 비고 : - * 추후 설치예정인 network plugin과 crio의 가상 인터페이스 충돌을 막기위해 cri-o의 default 인터페이스 설정을 제거한다. - ```bash - sudo rm -rf /etc/cni/net.d/100-crio-bridge.conf - sudo rm -rf /etc/cni/net.d/200-loopback.conf - ``` - * 폐쇄망 환경에서 private registry 접근을 위해 crio.conf 내용을 수정한다. - * insecure_registry, registries, plugin_dirs 내용을 수정한다. - * sudo vi /etc/crio/crio.conf - * registries = ["{registry}:{port}" , "docker.io"] - * insecure_registries = ["{registry}:{port}"] - * plugin_dirs : "/opt/cni/bin" 추가 - * (폐쇄망) pause_image : "k8s.gcr.io/pause:3.1" 을 "{registry}:{port}/k8s.gcr.io/pause:3.1" 로 변경 - ![image](figure/crio_config.PNG) - - * registries.conf 내용을 수정한다. - * sudo vi /etc/containers/registries.conf - ```bash - unqualified-search-registries = ['registry.fedoraproject.org', 'registry.access.redhat.com', 'registry.centos.org', 'docker.io', '{registry}:{port}'] - ex) unqualified-search-registries = ['registry.fedoraproject.org', 'registry.access.redhat.com', 'registry.centos.org', 'docker.io', '172.22.5.2:5000'] - ``` - * crio를 재시작 한다. - ```bash - sudo systemctl restart crio - ``` -## Step 2. kubeadm, kubelet, kubectl 설치 -* 목적 : `Kubernetes 구성을 위한 kubeadm, kubelet, kubectl 설치한다.` -* 순서: - * CRI-O 메이저와 마이너 버전은 쿠버네티스 메이저와 마이너 버전이 일치해야 한다. - * (폐쇄망) kubeadm, kubectl, kubelet 설치 (v1.17.6) - ```bash - sudo yum install -y kubeadm-1.17.6-0 kubelet-1.17.6-0 kubectl-1.17.6-0 - - sudo systemctl enable kubelet - ``` - * (외부망) 레포 등록 후 kubeadm, kubectl, kubelet 설치 (v1.17.6) - ```bash - sudo cat << "EOF" | sudo tee -a /etc/yum.repos.d/kubernetes.repo - [kubernetes] - name=Kubernetes - baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64 - enabled=1 - gpgcheck=1 - repo_gpgcheck=1 - gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg - EOF - - sudo yum install -y kubeadm-1.17.6-0 kubelet-1.17.6-0 kubectl-1.17.6-0 - - sudo systemctl enable kubelet - ``` - -## Step 3. kubernetes cluster 구성 -* 목적 : `kubernetes master를 구축한다.` -* 순서 : - * 쿠버네티스 설치시 필요한 kubeadm-config를 작성한다. - * vi kubeadm-config.yaml - ```bash - apiVersion: kubeadm.k8s.io/v1beta2 - kind: InitConfiguration - localAPIEndpoint: - advertiseAddress: {api server IP} - bindPort: 6443 - nodeRegistration: - criSocket: /var/run/crio/crio.sock - --- - apiVersion: kubeadm.k8s.io/v1beta2 - kind: ClusterConfiguration - kubernetesVersion: v1.17.6 - controlPlaneEndpoint: {endpoint IP}:6443 - imageRepository: {registry}/k8s.gcr.io - networking: - serviceSubnet: 10.96.0.0/16,fd00:10:96::/112 - podSubnet: 10.244.0.0/16,fd00:10:20::/72 - featureGates: - IPv6DualStack: true - --- - apiVersion: kubelet.config.k8s.io/v1beta1 - kind: KubeletConfiguration - cgroupDriver: systemd - --- - apiVersion: kubeproxy.config.k8s.io/v1alpha1 - kind: KubeProxyConfiguration - mode: ipvs - ``` - * kubernetesVersion : kubernetes version - * advertiseAddress : API server IP ( master IP ) - * 해당 master 노드의 IP - * controlPlaneEndpoint : endpoint IP ( master IP or virtual IP) , port는 반드시 6443으로 설정 - * 1개의 마스터 : master IP , 2개 이상의 마스터 구축시 : virtual IP - * serviceSubnet : "${SERVICE_IPV4_POOL}/${CIDR},${SERVICE_IPV6_POOL}/${CIDR}" - * podSubnet : "${POD_IPV4_POOL}/${CIDR},${POD_IPV6_POOL}/${CIDR}" - * imageRepository : "${registry} / docker hub name" - * IPv6DualStack: true, dual stack 기능이 베타 버전이라서 기본값으로는 비활성화이기 때문에 활성화 시키는 세팅(추후 기본으로 활성화 되면 빠져야 함) - * cgroupDriver: cgroup driver systemd 변경 - * mode: ipvs, dual stack 기능은 kube-proxy ipvs 모드에서만 동작 - - * kubeadm init (2개 이상 마스터 구축시에는 아래 가이드 참조) - ```bash - sudo kubeadm init --config=kubeadm-config.yaml - ``` - * 마스터 다중화 진행시 아래 마스터 다중화 가이드로 설치를 진행한다. - * [마스터 다중화 가이드](https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/K8S_Master#step-3-1-kubernetes-cluster-%EB%8B%A4%EC%A4%91%ED%99%94-%EA%B5%AC%EC%84%B1%EC%9D%84-%EC%9C%84%ED%95%9C-keepalived-%EC%84%A4%EC%B9%98) - - ![image](figure/kubeinit.PNG) - * kubernetes config - ```bash - mkdir -p $HOME/.kube - sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config - sudo chown $(id -u):$(id -g) $HOME/.kube/config - ``` - ![image](figure/success.PNG) - * 확인 - ```bash - kubectl get nodes - ``` - ![image](figure/nodes.PNG) - ```bash - kubectl get pods -A -o wide - ``` - ![image](figure/pods.PNG) -* 비고 : - * master에도 pod 스케줄을 가능하게 하려면 master taint를 제거한다 - ```bash - kubectl taint node [master hostname] node-role.kubernetes.io/master:NoSchedule- - ex) kubectl taint node k8s- node-role.kubernetes.io/master:NoSchedule- - ``` - -## Step 3-1. kubernetes cluster 다중화 구성을 위한 Keepalived 설치 -* 목적 : `K8S cluster의 Master 다중화 구성을 위한 Keepalived를 설치 및 설정한다` -* 순서 : - * Keepalived 설치 - ```bash - sudo yum install -y keepalived - ``` - - * Keepalived 설정 - ```bash - sudo vi /etc/keepalived/keepalived.conf - - vrrp_instance VI_1 { - state {MASTER or BACKUP} - interface {network interface} - virtual_router_id {virtual router id} - priority {priority} - advert_int 1 - nopreempt - authentication { - auth_type PASS - auth_pass $ place secure password here. - } - virtual_ipaddress { - {VIP} - } - } - ``` - ![image](figure/keepalived.PNG) - * interface : network interface 이름 확인 (ip a 명령어로 확인) ex) enp0s8 - * state : master or backup으로 설정, 하나의 master에만 master를 설정하고 나머지 master에는 backup으로 설정 - * priority : Master 우선순위 - * priority 값이 높으면 최우선적으로 Master 역할 수행 - * 각 Master마다 다른 priority 값으로 수정 - * ex) master1 priority 100, master2 priority 99, master3 priority 98 - * virtual_ipaddress : virtual ip(VIP) 설정 - * virtual_router_id : vritual router id ex) 50 - - * keepalived 재시작 및 상태 확인 - ```bash - sudo systemctl restart keepalived - sudo systemctl enable keepalived - sudo systemctl status keepalived - - ``` - - * network interface 확인 - ```bash - ip a - ``` - - * 설정한 VIP 확인 가능, 여러 마스터 중 하나만 보임. - * inet {VIP}/32 scope global eno1 - ![image](figure/ipa.PNG) - -## Step 3-2. docker 설치 및 설정 -* 목적 : `구성한 docker registry에 접근을 위해 docker를 설치한다.` -* 생성 순서 : - * 다른 구성하는 마스터에 docker를 설치한다. - ```bash - $ sudo yum install -y docker-ce - $ sudo systemctl start docker - $ sudo systemctl enable docker - ``` - * docker damon에 insecure-registries를 등록한다. - * sudo vi /etc/docker/daemon.json - ```bash - { - "insecure-registries": ["{IP}:5000"] - } - ``` - * docker를 재실행하고 status를 확인한다. - ```bash - $ sudo systemctl restart docker - $ sudo systemctl status docker - ``` - -## Step 3-3. kubernetes cluster 다중화 구성 설정 -* 목적 : `K8S cluster의 Master 다중화를 구성한다` -* 순서 : - * kubeadm-config.yaml 파일로 kubeadm 명령어 실행한다. - * Master 다중구성시 --upload-certs 옵션은 반드시 필요. - * join 시에 --cri-socket=/var/run/crio/crio.sock 옵션을 추가하여 실행한다. - ```bash - sudo kubeadm init --config=kubeadm-config.yaml --upload-certs - sudo kubeadm join {IP}:{PORT} --token ~~ discovery-token-ca-cert-hash --control-plane --certificate-key ~~ (1) --cri-socket=/var/run/crio/crio.sock - sudo kubeadm join {IP}:{PORT} --token ~~ discovery-token-ca-cert-hash --cri-socket=/var/run/crio/crio.sock (2) - ``` - ![image](figure/master2.PNG) - * 해당 옵션은 certificates를 control-plane으로 upload하는 옵션 - * 해당 옵션을 설정하지 않을 경우, 모든 Master 노드에서 key를 복사해야 함 - * Master 단일구성과는 다르게, --control-plane --certificate-key 옵션이 추가된 명령어가 출력됨 - * (1)처럼 Master 다중구성을 위한 hash 값을 포함한 kubeadm join 명령어가 출력되므로 해당 명령어를 복사하여 다중구성에 포함시킬 다른 Master에서 실행 - * (2)처럼 Worker의 join을 위한 명령어도 출력되므로 Worker 노드 join시 사용, crio 사용시 --cri-socket 옵션 추가 - ```bash - sudo kubeadm join 172.22.5.2:6443 --token 2cks7n.yvojnnnq1lyz1qud \ --discovery-token-ca-cert-hash sha256:efba18bb4862cbcb54fb643a1b7f91c25e08cfc1640e5a6fffa6de83e4c76f07 \ --control-plane --certificate-key f822617fcbfde09dff35c10e388bc881904b5b6c4da28f3ea8891db2d0bd3a62 --cri-socket=/var/run/crio/crio.sock - ``` - - * kubernetes config - ```bash - mkdir -p $HOME/.kube - sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config - sudo chown $(id -u):$(id -g) $HOME/.kube/config - ``` - -## 삭제 가이드 diff --git a/manifest/README.md b/manifest/README.md index 2b1b0e5..b89d37d 100644 --- a/manifest/README.md +++ b/manifest/README.md @@ -1,9 +1,5 @@ - - # k8s-master installer 사용법 -## 구성 요소 및 버전 - ## Prerequisites * 해당 installer는 폐쇄망 기준 가이드입니다. * OS 설치 및 package repo를 아래 가이드에 맞춰 설치합니다. @@ -13,8 +9,6 @@ * image registry에 이미지를 push 합니다. * https://github.com/tmax-cloud/hypercloud-install-guide/tree/master/K8S_Master#%ED%8F%90%EC%87%84%EB%A7%9D-%EC%84%A4%EC%B9%98-%EA%B0%80%EC%9D%B4%EB%93%9C -## 폐쇄망 설치 가이드 - ## Step0. k8s.config 설정 * 목적 : `k8s 설치 진행을 위한 k8s config 설정` * 순서 : @@ -38,3 +32,7 @@ ``` * 비고 : * k8s.config, k8s_infra_installer.sh파일과 yaml 디렉토리는 같은 디렉토리 내에에 있어야 합니다. + * runtime docker 이용시 아래의 명령어를 실행합니다. + ```bash + sudo ./k8s_infra_installer.sh up_docker + ``` diff --git a/manifest/k8s_infra_installer.sh b/manifest/k8s_infra_installer.sh index 145a374..a36c686 100644 --- a/manifest/k8s_infra_installer.sh +++ b/manifest/k8s_infra_installer.sh @@ -110,95 +110,164 @@ function install_crio() { sudo exit 100 fi +} +function install_docker() { + + echo "=========================================================================" + echo "========================== start install docker =========================" + echo "=========================================================================" + + #centos + if [[ ${os_check} == "\"CentOS Linux\"" ]]; then + + # install docker + sudo yum install -y docker + sudo systemctl start docker + sudo systemctl enable docker + + # check docker + sudo systemctl status docker + sudo rm -rf /etc/docker/daemon.json + + # edit docker config + sudo cat << "EOF" | sudo tee -a /etc/docker/daemon.json +{ + "insecure-registries": ["{imageRegistry}"] +} +EOF + sudo rm -rf ${yaml_dir}/kubeadm-config.yaml + # edit kubeadm config + sudo cat << "EOF" | sudo tee -a ${yaml_dir}/kubeadm-config.yaml +apiVersion: kubeadm.k8s.io/v1beta2 +kind: ClusterConfiguration +kubernetesVersion: {k8sVersion} +controlPlaneEndpoint: {apiServer}:6443 +imageRepository: {imageRegistry}/k8s.gcr.io +networking: +serviceSubnet: 10.96.0.0/16 +podSubnet: {podSubnet} +apiServer: +extraArgs: +advertise-address: {apiServer} +EOF + sudo sed -i "s|{imageRegistry}|${imageRegistry}|g" /etc/docker/daemon.json + sudo sed -i 's/registry.fedoraproject.org/{imageRegistry}/g' /etc/containers/registries.conf + sudo sed -i "s|{imageRegistry}|${imageRegistry}|g" /etc/containers/registries.conf + + sudo systemctl restart docker + + elif [[ ${os_check} = "\"Ubuntu\"" ]]; then + + # install docker + sudo apt-get -y install docker + sudo systemctl enable docker.service + sudo systemctl start docker.service + + # check docker + sudo systemctl status docker + + # others + else + sudo echo "This OS is not supported." + sudo exit 100 + fi } function install_kube() { - echo "=========================================================================" + echo "=========================================================================" echo "======================= start install kubernetes ======================" echo "=========================================================================" #install kubernetes if [[ -z ${k8sVersion} ]]; then - k8sVersion=1.17.6 + k8sVersion=1.17.6 else - k8sVersion=${k8sVersion} + k8sVersion=${k8sVersion} fi if [[ -z ${apiServer} ]]; then - apiServer=127.0.0.1 + apiServer=127.0.0.1 else - apiServer=${apiServer} + apiServer=${apiServer} fi if [[ -z ${podSubnet} ]]; then - podSubnet=10.244.0.0/16 + podSubnet=10.244.0.0/16 else - podSubnet=${podSubnet} + podSubnet=${podSubnet} fi # centos if [[ ${os_check} == "\"CentOS Linux\"" ]]; then - #install kubernetes components - sudo yum install -y kubeadm-${k8sVersion}-0 kubelet-${k8sVersion}-0 kubectl-${k8sVersion}-0 - sudo systemctl enable --now kubelet + #install kubernetes components + sudo yum install -y kubeadm-${k8sVersion}-0 kubelet-${k8sVersion}-0 kubectl-${k8sVersion}-0 + sudo systemctl enable --now kubelet # ubuntu elif [[ ${os_check} = "\"Ubuntu\"" ]]; then - #install kubernetes components - sudo apt-get install -y kubeadm-${k8sVersion}-0 kubelet-${k8sVersion}-0 kubectl-${k8sVersion}-0 - sudo systemctl enable kubelet + #install kubernetes components + sudo apt-get install -y kubeadm-${k8sVersion}-0 kubelet-${k8sVersion}-0 kubectl-${k8sVersion}-0 + sudo systemctl enable kubelet # others else echo "This OS is not supported." exit 100 fi - sudo echo '1' > /proc/sys/net/ipv4/ip_forward - sudo echo '1' > /proc/sys/net/bridge/bridge-nf-call-iptables + sudo echo '1' > /proc/sys/net/ipv4/ip_forward + sudo echo '1' > /proc/sys/net/bridge/bridge-nf-call-iptables - #change kubeadm yaml - sudo sed -i "s|{k8sVersion}|v${k8sVersion}|g" ${yaml_dir}/kubeadm-config.yaml - sudo sed -i "s|{apiServer}|${apiServer}|g" ${yaml_dir}/kubeadm-config.yaml - sudo sed -i "s|{podSubnet}|\"${podSubnet}\"|g" ${yaml_dir}/kubeadm-config.yaml - sudo sed -i "s|{imageRegistry}|${imageRegistry}|g" ${yaml_dir}/kubeadm-config.yaml + #change kubeadm yaml + sudo sed -i "s|{k8sVersion}|v${k8sVersion}|g" ${yaml_dir}/kubeadm-config.yaml + sudo sed -i "s|{apiServer}|${apiServer}|g" ${yaml_dir}/kubeadm-config.yaml + sudo sed -i "s|{podSubnet}|${podSubnet}|g" ${yaml_dir}/kubeadm-config.yaml + sudo sed -i "s|{imageRegistry}|${imageRegistry}|g" ${yaml_dir}/kubeadm-config.yaml - # kube init - sudo kubeadm init --config=${yaml_dir}/kubeadm-config.yaml --upload-certs + # kube init + sudo kubeadm init --config=${yaml_dir}/kubeadm-config.yaml --upload-certs - mkdir -p $HOME/.kube - sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config - sudo chown $(id -u):$(id -g) $HOME/.kube/config + mkdir -p $HOME/.kube + sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config + sudo chown $(id -u):$(id -g) $HOME/.kube/config - echo "=========================================================================" - echo "====================== complete install kubernetes ====================" - echo "=========================================================================" + echo "=========================================================================" + echo "====================== complete install kubernetes ====================" + echo "=========================================================================" } function uninstall() { - kubeadm reset -f - - sudo sed -i "s|v${k8sVersion}|{k8sVersion}|g" ${yaml_dir}/kubeadm-config.yaml - sudo sed -i "s|${apiServer}|{apiServer}|g" ${yaml_dir}/kubeadm-config.yaml - sudo sed -i "s|\"${podSubnet}\"|{podSubnet}|g" ${yaml_dir}/kubeadm-config.yaml - sudo sed -i "s|${imageRegistry}|{imageRegistry}|g" ${yaml_dir}/kubeadm-config.yaml - sudo rm -rf $HOME/.kube + + kubeadm reset --cri-socket=/var/run/crio/crio.sock + + sudo yum remove -y kubeadm-1.17.6-0 kubelet-1.17.6-0 kubectl-1.17.6-0 + sudo yum remove -y crio or sudo yum remove -y docker-ce + sudo yum remove -y keepalived + + echo "=========================================================================" + echo "===================== uninstall kubernetes success ====================" + echo "=========================================================================" } function main(){ - + case "${1:-}" in up) set_env install_crio install_kube ;; + up_docker) + set_env + install_docker + install_kube + ;; delete) uninstall ;; @@ -206,6 +275,7 @@ function main(){ set +x echo " service list:" >&2 echo " $0 up" >&2 + echo " $0 up_docker" >&2 echo " $0 delete" >&2 ;; esac diff --git a/manifest/yaml/haproxy.cfg b/manifest/yaml/haproxy.cfg new file mode 100644 index 0000000..e05c91a --- /dev/null +++ b/manifest/yaml/haproxy.cfg @@ -0,0 +1,28 @@ +global + log 127.0.0.1 local2 + maxconn 2000 + uid 0 + gid 0 + daemon # background process + +defaults + log global # global 설정 사용 + mode tcp # SSL 통신을 위해서는 TCP모드로 (http모드는 SSL 안됨) + option tcplog + option dontlognull # 데이터가 전송되지 않은 연결 로깅 제외 + retries 3 # 연결요청 재시도 횟수 + maxconn 2000 #option redispatch + timeout connect 10s + timeout client 1m + timeout server 1m + +frontend k8s-api + bind 0.0.0.0:6443 + default_backend k8s-api + +backend k8s-api + option tcp-check + balance roundrobin + server MASTER1NAME MASTER1IP check # Master 다중화 서버들 정보 기재 + server MASTER2NAME MASTER2IP check + server MASTER3NAME MASTER3IP check diff --git a/manifest/yaml/keepalived.conf b/manifest/yaml/keepalived.conf new file mode 100644 index 0000000..da1e79f --- /dev/null +++ b/manifest/yaml/keepalived.conf @@ -0,0 +1,47 @@ +global_defs { + script_user root root + enable_script_security off +} + +vrrp_script chk_haproxy { + script "/usr/sbin/pidof haproxy" + interval 2 + weight 2 +} + +vrrp_instance VI_1 { + state MASTER # MASTER는 메인 LB, 백업 LB는 BACKUP 으로 설정 + interface enp0s8 # 사용할 interface + virtual_router_id 51 + priority 100 # MASTER의 우선순위가 적어도 1이상 높아야 함 + advert_int 1 + nopreempt + authentication { # 인증에 사용될 password(동일하게 맞춰주기만 하면 됨) + auth_type PASS + auth_pass 1111 + } + + unicast_src_ip LB1 # LB 서버 local ip + + unicast_peer { + LB2 # 다른 LB 서버 local ip + } + + virtual_ipaddress { + VIP # 클러스터 구성에 사용될 VIP! + } + + notify_master "/bin/sh /etc/keepalived/notify_action.sh MASTER" + notify_backup "/bin/sh /etc/keepalived/notify_action.sh BACKUP" + notify_fault "/bin/sh /etc/keepalived/notify_action.sh FAULT" + notify_stop "/bin/sh /etc/keepalived/notify_action.sh STOP" + + track_script { + chk_haproxy + } + + track_interface { + enp0s8 # 사용할 interface + } + +} diff --git a/manifest/yaml/lb_set_script.sh b/manifest/yaml/lb_set_script.sh new file mode 100644 index 0000000..c8a61f5 --- /dev/null +++ b/manifest/yaml/lb_set_script.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +pkg_check=`which rpm >& /dev/null; echo $?` + +rpm_pkg_list=("keepalived" "haproxy") +#rpm_need_install="yum install -y" +#dpkg_need_install=`apt-get install` + +for pkgname in ${rpm_pkg_list[@]}; +do + #pkg_check_cmd=`rpm -qa | grep "${list_num}" >& /dev/null; echo $?` + #if [ ${pkg_check_cmd} -eq 0 ]; + #then + rpm_need_install="yum install -y ${pkgname}" + ${rpm_need_install} 2>&1 > /dev/null + #else + # echo "${pkgname} is already installed!!" + #fi +done + +SCRIPTPATH=$(dirname `which $0`) + +THISPATH=`echo $SCRIPTPATH` + +cp ${THISPATH}/notify_action.sh /etc/keepalived/notify_action.sh +mv /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf_back +cp -f ${THISPATH}/keepalived.conf /etc/keepalived/keepalived.conf + +sed -i 's/LB1/'"$LB1"'/' /etc/keepalived/keepalived.conf +sed -i 's/LB2/'"$LB2"'/' /etc/keepalived/keepalived.conf + +sed -i 's/VIP/'"$VIP"'/' /etc/keepalived/keepalived.conf + +mv /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg_back +cp -f ${THISPATH}/haproxy.cfg /etc/haproxy/haproxy.cfg + +sed -i 's/MASTER1NAME/'"$MASTER1NAME"'/' /etc/haproxy/haproxy.cfg +sed -i 's/MASTER2NAME/'"$MASTER2NAME"'/' /etc/haproxy/haproxy.cfg +sed -i 's/MASTER3NAME/'"$MASTER3NAME"'/' /etc/haproxy/haproxy.cfg + +sed -i 's/MASTER1IP/'"$MASTER1IP"'/' /etc/haproxy/haproxy.cfg +sed -i 's/MASTER2IP/'"$MASTER2IP"'/' /etc/haproxy/haproxy.cfg +sed -i 's/MASTER3IP/'"$MASTER3IP"'/' /etc/haproxy/haproxy.cfg diff --git a/manifest/yaml/notify_action.sh b/manifest/yaml/notify_action.sh new file mode 100644 index 0000000..a6a4c3e --- /dev/null +++ b/manifest/yaml/notify_action.sh @@ -0,0 +1,35 @@ +#!/bin/bash +#/etc/keepalived/notify_action.sh +log_file=/var/log/keepalived.log +log_write() +{ + echo "[`date '+%Y-%m-%d %T'`] $1" >> $log_file +} + +[ ! -d /var/keepalived/ ] && mkdir -p /var/keepalived/ + +case "$1" in + "MASTER" ) + echo -n "$1" > /var/keepalived/state + log_write " notify_master" + echo -n "0" > /var/keepalived/vip_check_failed_count + ;; + + "BACKUP" ) + echo -n "$1" > /var/keepalived/state + log_write " notify_backup" + ;; + + "FAULT" ) + echo -n "$1" > /var/keepalived/state + log_write " notify_fault" + ;; + + "STOP" ) + echo -n "$1" > /var/keepalived/state + log_write " notify_stop" + ;; + *) + log_write "notify_action.sh: STATE ERROR!!!" + ;; +esac diff --git a/manifest/yaml/remote_lb_set_script.sh b/manifest/yaml/remote_lb_set_script.sh new file mode 100644 index 0000000..2802fdb --- /dev/null +++ b/manifest/yaml/remote_lb_set_script.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +exp=$HOME/archive/keepalived_script/ssh_login.exp +expcopy=$HOME/archive/keepalived_script/scp_copy.exp +exprestart=$HOME/archive/keepalived_script/restart_pkg.exp +account=${RUSER} #root #${1} +password=${RUSERPWD} #1234 #${2} +#ipaddr="192.168.56.250 192.168.56.130" #${3} +ipaddr="${LB1} ${LB2}" +#masteripaddr="${MASTER1} ${MASTER2} ${MASTER3}" + +pkglist=("keepalived" "haproxy") + +for svr in $ipaddr +do + case "${svr}" in + *) + for pkgname in ${pkglist[@]}; + do + $exp $account $password ${svr} ${pkgname}; + + if [ "${pkgname}" == "keepalived" ]; then + $expcopy $account $password ${svr} ${pkgname} ${pkgname}.conf ${MASTER1NAME} ${MASTER2NAME} ${MASTER3NAME} ${MASTER1IP} ${MASTER2IP} ${MASTER3IP} ${LB1} ${LB2} ${VIP} + elif [ "${pkgname}" == "haproxy" ]; then + $expcopy $account $password ${svr} ${pkgname} ${pkgname}.cfg ${MASTER1NAME} ${MASTER2NAME} ${MASTER3NAME} ${MASTER1IP} ${MASTER2IP} ${MASTER3IP} ${LB1} ${LB2} ${VIP} + fi + + $exprestart $account $password ${svr} ${pkgname}; + done + ;; + esac + sleep 0.5 + +done diff --git a/manifest/yaml/restart_pkg.exp b/manifest/yaml/restart_pkg.exp new file mode 100644 index 0000000..c1d58ac --- /dev/null +++ b/manifest/yaml/restart_pkg.exp @@ -0,0 +1,39 @@ +#!/usr/bin/expect + +set username [lindex $argv 0] +set password [lindex $argv 1] +set hostname [lindex $argv 2] +set pkgname [lindex $argv 3] +set timeout 5 + +if {[llength $argv] == 0} { + send_user "Usage: scriptname username \'password\' hostname \n" + exit 1 +} +send_user "\n\n#######################\n Try to connect server \n#######################\n\n" + +spawn ssh -o StrictHostKeyChecking=no $username@$hostname +expect { + "password:" { send "$password\r"; exp_continue } + "Last login:" { send_user "\n\n#######################\n SSH is success \n Pkg checking \n#######################\n\n"; exp_continue } +} +#expect -re "Last login:" +#send_user "\n\n#######################\n SSH is success \n Pkg checking \n#######################\n\n" + +send "sudo systemctl enable ${pkgname}\r\n" +expect { + "password:" { send "$password\r"; exp_continue } + "Created symlink from" { send "sudo systemctl daemon-reload\r\n"; exp_continue } +} + +send "sudo systemctl restart ${pkgname}\r\n" + +send "sudo systemctl status ${pkgname}\r\n" +expect { + "Active: active (running)" { send_user "\n\n#######################\n Pkg Start Normal \n#######################\n\n"; exp_continue } +} + +send_user "\n\n#######################\n Done \n#######################\n\n" + +send "exit \r" +expect eof diff --git a/manifest/yaml/scp_copy.exp b/manifest/yaml/scp_copy.exp new file mode 100644 index 0000000..da9d987 --- /dev/null +++ b/manifest/yaml/scp_copy.exp @@ -0,0 +1,48 @@ +#!/usr/bin/expect + +set username [lindex $argv 0] +set password [lindex $argv 1] +set hostname [lindex $argv 2] +set pkgname [lindex $argv 3] +set configfile [lindex $argv 4] +set master1name [lindex $argv 5] +set master2name [lindex $argv 6] +set master3name [lindex $argv 7] +set master1ip [lindex $argv 8] +set master2ip [lindex $argv 9] +set master3ip [lindex $argv 10] +set lb1 [lindex $argv 11] +set lb2 [lindex $argv 12] +set vip [lindex $argv 13] +#set pkgname {echo $configfile | awk -F'.' '{print $1, $2}'} + +if {[llength $argv] == 0} { + send_user "Usage: scriptname username \'password\' hostname \n" + exit 1 +} +send_user "\n\n#######################\n Trying to transfer files \n#######################\n\n" + +set timeout 5; +#split($configfile, arr, "."); +#if {$pkgname[0] == "keepalived"} { +# spawn scp $configfile $username@$hostname:/home/etc/$pkgname[0]/$configfile +#} elseif {$pkgname[0] == "haproxy"} { +# spawn scp $configfile $username@$hostname:/home/etc/$pkgname[0]/$configfile +#} + +if {$pkgname == "keepalived"} { + spawn scp notify_action.sh $username@$hostname:/etc/$pkgname/ + expect { + "password:" { send "$password\r"; exp_continue }; + } +} + +spawn scp $configfile $username@$hostname:/home/etc/$pkgname/$configfile +#spawn scp $configfile $username@$hostname:/home/ +expect { + "password:" { send "$password\r"; exp_continue }; + "*100\%" { send_user "\n\n#######################\n Copy success \n#######################\n\n"; exp_continue } +} + +send + diff --git a/manifest/yaml/ssh_login.exp b/manifest/yaml/ssh_login.exp new file mode 100644 index 0000000..d342568 --- /dev/null +++ b/manifest/yaml/ssh_login.exp @@ -0,0 +1,39 @@ +#!/usr/bin/expect + +set username [lindex $argv 0] +set password [lindex $argv 1] +set hostname [lindex $argv 2] +set pkgname [lindex $argv 3] +set timeout 5 + + +if {[llength $argv] == 0} { + send_user "Usage: scriptname username \'password\' hostname \n" + exit 1 +} +send_user "\n\n#######################\n Try to connect server \n#######################\n\n" + +spawn ssh -o StrictHostKeyChecking=no $username@$hostname +expect { + "password:" { send "$password\r"; exp_continue } + "Last login:" { send_user "\n\n#######################\n SSH is success \n Pkg checking \n#######################\n\n"; exp_continue } +} +#expect -re "Last login:" +#send_user "\n\n#######################\n SSH is success \n Pkg checking \n#######################\n\n" + +send "rpm -q ${pkgname}\r\n" +expect { + "package ${pkgname} is not installed" { set timeout 20; send "yum install -y ${pkgname}\r\n"; expect { "Complete!"; exp_continue } } +} + +set timeout 5; +if {$pkgname == "keepalived"} { + send "cp -y /etc/$pkgname/$pkgname.conf /etc/$pkgname/$pkgname.conf_back\r\n" +} elseif {$pkgname == "haproxy"} { + send "cp -y /etc/$pkgname/$pkgname.cfg /etc/$pkgname/$pkgname.cfg_back\r\n" +} + +send_user "\n\n#######################\n Done \n#######################\n\n" + +send "exit \r" +expect eof