컨테이너&가상화
CRI-O기반의 k8s설치
잘나가는전산쟁이
2022. 7. 22. 02:27
728x90
반응형
사전사항
- OS환경설정
1
$> swapoff -a23$> cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf4br_netfilter5EOF67$> cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf8net.bridge.bridge-nf-call-ip6tables = 19net.bridge.bridge-nf-call-iptables = 110EOF1112$> sudo sysctl --system - crio / kubernetees 패키지 리포지터리 구성
1
$> cat /etc/yum.repos.d/libcontainers.repo2[devel_kubic_libcontainers_stable]3name=Stable Releases of Upstream github.com/containers packages (CentOS_8)4type=rpm-md5baseurl=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/CentOS_8/6gpgcheck=17gpgkey=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/CentOS_8/repodata/repomd.xml.key8enabled=11$> cat /etc/yum.repos.d/cri-o-1.23.repo2[devel_kubic_libcontainers_stable_cri-o_1.23]3name=devel:kubic:libcontainers:stable:cri-o:1.23 (CentOS_8)4type=rpm-md5baseurl=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable:/cri-o:/1.23/CentOS_8/6gpgcheck=17gpgkey=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable:/cri-o:/1.23/CentOS_8/repodata/repomd.xml.key8enabled=11$> cat /etc/yum.repos.d/kubernetes.repo2[kubernetes]3name=Kubernetes4baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-$basearch5enabled=16gpgcheck=17repo_gpgcheck=18gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg - 패키지 설치
1
$> yum install kubelet kubeadm kubectl libcgroup cri-o cri-tools -y2$> systemctl enable crio --now3$> systemctl enable kubelet
클러스터 생성 (control palin 1번에서만 수행)
- kubeadm 클러스터 생성
1
$> kubeadm init --control-plane-endpoint 172.21.107.238:6443 --pod-network-cidr 10.250.0.0/16 --ignore-preflight-errors=all --upload-certs23## 결과값중에 control / worker 노드별 join 명령이 다르기 때문에 별도로 복사해놓어야 함
##Control node용1$> kubeadm join 172.21.107.238:6443 --token abcd \2--discovery-token-ca-cert-hash sha256:yyy \3--control-plane --certificate-key zzz
## Worker Node용1$> kubeadm join 172.21.107.238:6443 --token abcd \2--discovery-token-ca-cert-hash sha256:yyyy \3--ignore-preflight-errors=all - 인증서 정보 복사
1
$> mkdir -p $HOME/.kube2$> /bin/cp /etc/kubernetes/admin.conf $HOME/.kube/config3$> chown $(id -u):$(id -g) $HOME/.kube/config4$> export KUBECONFIG=/etc/kubernetes/admin.conf - CNI 설치(Calico)
1
$> curl https://projectcalico.docs.tigera.io/manifests/calico.yaml -O2$> kubectl apply -f calico.yaml
클러스터 연동
- 타 Control plain 연동 (Control Plain 한대씩 순차 작업 수행)
1
$> kubeadm join 172.21.107.238:6443 --token abcd \2--discovery-token-ca-cert-hash sha256:yyy \3--control-plane --certificate-key zzz - 노드 연동 확인 (Control plain에서 수행)
1
$> kubectl get no2NAME STATUS ROLES AGE VERSION3k8stesttx-k8s-master-dev01 Ready control-plane,master 3h6m v1.23.54k8stesttx-k8s-master-dev02 Ready control-plane,master 3h6m v1.23.55k8stesttx-k8s-master-dev03 Ready control-plane,master 3h6m v1.23.5 - Worker Node 연동
1
$> kubeadm join 172.21.107.238:6443 --token abcd \2--discovery-token-ca-cert-hash sha256:yyyy \3--ignore-preflight-errors=all - 노드 연동 확인 (Control plain에서 수행)
1
$> kubectl get no2NAME STATUS ROLES AGE VERSION3...4k8stesttx-k8s-worker-dev01 Ready <none> 40m v1.23.55k8stesttx-k8s-worker-dev02 Ready <none> 40m v1.23.56k8stesttx-k8s-worker-dev03 Ready <none> 40m v1.23.5
k8s 인증서 10년으로 연장
- 인증서 연장 스크립트
1
#!/usr/bin/env bash23set -o errexit4set -o pipefail5# set -o xtrace67# set output color8NC='\033[0m'9RED='\033[31m'10GREEN='\033[32m'11YELLOW='\033[33m'12BLUE='\033[34m'1314log::err() {15printf "[$(date +'%Y-%m-%dT%H:%M:%S.%2N%z')][${RED}ERROR${NC}] %b\n" "$@"16}1718log::info() {19printf "[$(date +'%Y-%m-%dT%H:%M:%S.%2N%z')][INFO] %b\n" "$@"20}2122log::warning() {23printf "[$(date +'%Y-%m-%dT%H:%M:%S.%2N%z')][${YELLOW}WARNING${NC}] \033[0m%b\n" "$@"24}2526check_file() {27if [[ ! -r ${1} ]]; then28log::err "can not find ${1}"29exit 130fi31}3233# get x509v3 subject alternative name from the old certificate34cert::get_subject_alt_name() {35local cert=${1}.crt36local alt_name3738check_file "${cert}"39alt_name=$(openssl x509 -text -noout -in "${cert}" | grep -A1 'Alternative' | tail -n1 | sed 's/[[:space:]]*Address//g')40printf "%s\n" "${alt_name}"41}4243# get subject from the old certificate44cert::get_subj() {45local cert=${1}.crt46local subj4748check_file "${cert}"49subj=$(openssl x509 -text -noout -in "${cert}" | grep "Subject:" | sed 's/Subject:/\//g;s/\,/\//;s/[[:space:]]//g')50printf "%s\n" "${subj}"51}5253cert::backup_file() {54local file=${1}55if [[ ! -e ${file}.old-$(date +%Y%m%d) ]]; then56cp -rp "${file}" "${file}.old-$(date +%Y%m%d)"57log::info "backup ${file} to ${file}.old-$(date +%Y%m%d)"58else59log::warning "does not backup, ${file}.old-$(date +%Y%m%d) already exists"60fi61}6263# check certificate expiration64cert::check_cert_expiration() {65local cert=${1}.crt66local cert_expires6768cert_expires=$(openssl x509 -text -noout -in "${cert}" | awk -F ": " '/Not After/{print$2}')69printf "%s\n" "${cert_expires}"70}7172# check kubeconfig expiration73cert::check_kubeconfig_expiration() {74local config=${1}.conf75local cert76local cert_expires7778cert=$(grep "client-certificate-data" "${config}" | awk '{print$2}' | base64 -d)79cert_expires=$(openssl x509 -text -noout -in <(printf "%s" "${cert}") | awk -F ": " '/Not After/{print$2}')80printf "%s\n" "${cert_expires}"81}8283# check etcd certificates expiration84cert::check_etcd_certs_expiration() {85local cert86local certs8788certs=(89"${ETCD_CERT_CA}"90"${ETCD_CERT_SERVER}"91"${ETCD_CERT_PEER}"92"${ETCD_CERT_HEALTHCHECK_CLIENT}"93"${ETCD_CERT_APISERVER_ETCD_CLIENT}"94)9596for cert in "${certs[@]}"; do97if [[ ! -r ${cert} ]]; then98printf "%-50s%-30s\n" "${cert}.crt" "$(cert::check_cert_expiration "${cert}")"99fi100done101}102103# check master certificates expiration104cert::check_master_certs_expiration() {105local certs106local kubeconfs107local cert108local conf109110certs=(111"${CERT_CA}"112"${CERT_APISERVER}"113"${CERT_APISERVER_KUBELET_CLIENT}"114"${FRONT_PROXY_CA}"115"${FRONT_PROXY_CLIENT}"116)117118kubeconfs=(119"${CONF_CONTROLLER_MANAGER}"120"${CONF_SCHEDULER}"121"${CONF_ADMIN}"122)123124printf "%-50s%-30s\n" "CERTIFICATE" "EXPIRES"125126for conf in "${kubeconfs[@]}"; do127if [[ ! -r ${conf} ]]; then128printf "%-50s%-30s\n" "${conf}.config" "$(cert::check_kubeconfig_expiration "${conf}")"129fi130done131132for cert in "${certs[@]}"; do133if [[ ! -r ${cert} ]]; then134printf "%-50s%-30s\n" "${cert}.crt" "$(cert::check_cert_expiration "${cert}")"135fi136done137}138139# check all certificates expiration140cert::check_all_expiration() {141cert::check_master_certs_expiration142cert::check_etcd_certs_expiration143}144145# generate certificate whit client, server or peer146# Args:147# $1 (the name of certificate)148# $2 (the type of certificate, must be one of client, server, peer)149# $3 (the subject of certificates)150# $4 (the validity of certificates) (days)151# $5 (the name of ca)152# $6 (the x509v3 subject alternative name of certificate when the type of certificate is server or peer)153cert::gen_cert() {154local cert_name=${1}155local cert_type=${2}156local subj=${3}157local cert_days=${4}158local ca_name=${5}159local alt_name=${6}160local ca_cert=${ca_name}.crt161local ca_key=${ca_name}.key162local cert=${cert_name}.crt163local key=${cert_name}.key164local csr=${cert_name}.csr165local common_csr_conf='distinguished_name = dn\n[dn]\n[v3_ext]\nkeyUsage = critical, digitalSignature, keyEncipherment\n'166167for file in "${ca_cert}" "${ca_key}" "${cert}" "${key}"; do168check_file "${file}"169done170171case "${cert_type}" in172client)173csr_conf=$(printf "%bextendedKeyUsage = clientAuth\n" "${common_csr_conf}")174;;175server)176csr_conf=$(printf "%bextendedKeyUsage = serverAuth\nsubjectAltName = %b\n" "${common_csr_conf}" "${alt_name}")177;;178peer)179csr_conf=$(printf "%bextendedKeyUsage = serverAuth, clientAuth\nsubjectAltName = %b\n" "${common_csr_conf}" "${alt_name}")180;;181*)182log::err "unknow, unsupported certs type: ${YELLOW}${cert_type}${NC}, supported type: client, server, peer"183exit 1184;;185esac186187# gen csr188openssl req -new -key "${key}" -subj "${subj}" -reqexts v3_ext \189-config <(printf "%b" "${csr_conf}") \190-out "${csr}" >/dev/null 2>&1191# gen cert192openssl x509 -in "${csr}" -req -CA "${ca_cert}" -CAkey "${ca_key}" -CAcreateserial -extensions v3_ext \193-extfile <(printf "%b" "${csr_conf}") \194-days "${cert_days}" -out "${cert}" >/dev/null 2>&1195196rm -f "${csr}"197}198199cert::update_kubeconf() {200local cert_name=${1}201local kubeconf_file=${cert_name}.conf202local cert=${cert_name}.crt203local key=${cert_name}.key204local subj205local cert_base64206207check_file "${kubeconf_file}"208# get the key from the old kubeconf209grep "client-key-data" "${kubeconf_file}" | awk '{print$2}' | base64 -d >"${key}"210# get the old certificate from the old kubeconf211grep "client-certificate-data" "${kubeconf_file}" | awk '{print$2}' | base64 -d >"${cert}"212# get subject from the old certificate213subj=$(cert::get_subj "${cert_name}")214cert::gen_cert "${cert_name}" "client" "${subj}" "${CERT_DAYS}" "${CERT_CA}"215# get certificate base64 code216cert_base64=$(base64 -w 0 "${cert}")217218# set certificate base64 code to kubeconf219sed -i 's/client-certificate-data:.*/client-certificate-data: '"${cert_base64}"'/g' "${kubeconf_file}"220221rm -f "${cert}"222rm -f "${key}"223}224225cert::update_etcd_cert() {226local subj227local subject_alt_name228local cert229230# generate etcd server,peer certificate231# /etc/kubernetes/pki/etcd/server232# /etc/kubernetes/pki/etcd/peer233for cert in ${ETCD_CERT_SERVER} ${ETCD_CERT_PEER}; do234subj=$(cert::get_subj "${cert}")235subject_alt_name=$(cert::get_subject_alt_name "${cert}")236cert::gen_cert "${cert}" "peer" "${subj}" "${CERT_DAYS}" "${ETCD_CERT_CA}" "${subject_alt_name}"237log::info "${GREEN}updated ${BLUE}${cert}.conf${NC}"238done239240# generate etcd healthcheck-client,apiserver-etcd-client certificate241# /etc/kubernetes/pki/etcd/healthcheck-client242# /etc/kubernetes/pki/apiserver-etcd-client243for cert in ${ETCD_CERT_HEALTHCHECK_CLIENT} ${ETCD_CERT_APISERVER_ETCD_CLIENT}; do244subj=$(cert::get_subj "${cert}")245cert::gen_cert "${cert}" "client" "${subj}" "${CERT_DAYS}" "${ETCD_CERT_CA}"246log::info "${GREEN}updated ${BLUE}${cert}.conf${NC}"247done248249# restart etcd250docker ps | awk '/k8s_etcd/{print$1}' | xargs -r -I '{}' docker restart {} >/dev/null 2>&1 || true251log::info "restarted etcd"252}253254cert::update_master_cert() {255local subj256local subject_alt_name257local conf258259# generate apiserver server certificate260# /etc/kubernetes/pki/apiserver261subj=$(cert::get_subj "${CERT_APISERVER}")262subject_alt_name=$(cert::get_subject_alt_name "${CERT_APISERVER}")263cert::gen_cert "${CERT_APISERVER}" "server" "${subj}" "${CERT_DAYS}" "${CERT_CA}" "${subject_alt_name}"264log::info "${GREEN}updated ${BLUE}${CERT_APISERVER}.crt${NC}"265266# generate apiserver-kubelet-client certificate267# /etc/kubernetes/pki/apiserver-kubelet-client268subj=$(cert::get_subj "${CERT_APISERVER_KUBELET_CLIENT}")269cert::gen_cert "${CERT_APISERVER_KUBELET_CLIENT}" "client" "${subj}" "${CERT_DAYS}" "${CERT_CA}"270log::info "${GREEN}updated ${BLUE}${CERT_APISERVER_KUBELET_CLIENT}.crt${NC}"271272# generate kubeconf for controller-manager,scheduler and kubelet273# /etc/kubernetes/controller-manager,scheduler,admin,kubelet.conf274for conf in ${CONF_CONTROLLER_MANAGER} ${CONF_SCHEDULER} ${CONF_ADMIN} ${CONF_KUBELET}; do275if [[ ${conf##*/} == "kubelet" ]]; then276# https://github.com/kubernetes/kubeadm/issues/1753277set +e278grep kubelet-client-current.pem /etc/kubernetes/kubelet.conf >/dev/null 2>&1279kubelet_cert_auto_update=$?280set -e281if [[ "$kubelet_cert_auto_update" == "0" ]]; then282log::info "does not need to update kubelet.conf"283continue284fi285fi286287# update kubeconf288cert::update_kubeconf "${conf}"289log::info "${GREEN}updated ${BLUE}${conf}.conf${NC}"290291# copy admin.conf to ${HOME}/.kube/config292if [[ ${conf##*/} == "admin" ]]; then293mkdir -p "${HOME}/.kube"294local config=${HOME}/.kube/config295local config_backup296config_backup=${HOME}/.kube/config.old-$(date +%Y%m%d)297if [[ -f ${config} ]] && [[ ! -f ${config_backup} ]]; then298cp -fp "${config}" "${config_backup}"299log::info "backup ${config} to ${config_backup}"300fi301cp -fp "${conf}.conf" "${HOME}/.kube/config"302log::info "copy the admin.conf to ${HOME}/.kube/config"303fi304done305306# generate front-proxy-client certificate307# /etc/kubernetes/pki/front-proxy-client308subj=$(cert::get_subj "${FRONT_PROXY_CLIENT}")309cert::gen_cert "${FRONT_PROXY_CLIENT}" "client" "${subj}" "${CERT_DAYS}" "${FRONT_PROXY_CA}"310log::info "${GREEN}updated ${BLUE}${FRONT_PROXY_CLIENT}.crt${NC}"311312# restart apiserver, controller-manager, scheduler and kubelet313for item in "apiserver" "controller-manager" "scheduler"; do314docker ps | awk '/k8s_kube-'${item}'/{print$1}' | xargs -r -I '{}' docker restart {} >/dev/null 2>&1 || true315log::info "restarted ${item}"316done317systemctl restart kubelet || true318log::info "restarted kubelet"319}320321main() {322local node_type=$1323324CERT_DAYS=3650325326KUBE_PATH=/etc/kubernetes327PKI_PATH=${KUBE_PATH}/pki328329# master certificates path330# apiserver331CERT_CA=${PKI_PATH}/ca332CERT_APISERVER=${PKI_PATH}/apiserver333CERT_APISERVER_KUBELET_CLIENT=${PKI_PATH}/apiserver-kubelet-client334CONF_CONTROLLER_MANAGER=${KUBE_PATH}/controller-manager335CONF_SCHEDULER=${KUBE_PATH}/scheduler336CONF_ADMIN=${KUBE_PATH}/admin337CONF_KUBELET=${KUBE_PATH}/kubelet338# front-proxy339FRONT_PROXY_CA=${PKI_PATH}/front-proxy-ca340FRONT_PROXY_CLIENT=${PKI_PATH}/front-proxy-client341342# etcd certificates path343ETCD_CERT_CA=${PKI_PATH}/etcd/ca344ETCD_CERT_SERVER=${PKI_PATH}/etcd/server345ETCD_CERT_PEER=${PKI_PATH}/etcd/peer346ETCD_CERT_HEALTHCHECK_CLIENT=${PKI_PATH}/etcd/healthcheck-client347ETCD_CERT_APISERVER_ETCD_CLIENT=${PKI_PATH}/apiserver-etcd-client348349case ${node_type} in350# etcd)351# # update etcd certificates352# cert::update_etcd_cert353# ;;354master)355# check certificates expiration356cert::check_master_certs_expiration357# backup $KUBE_PATH to $KUBE_PATH.old-$(date +%Y%m%d)358cert::backup_file "${KUBE_PATH}"359# update master certificates and kubeconf360log::info "${GREEN}updating...${NC}"361cert::update_master_cert362log::info "${GREEN}done!!!${NC}"363# check certificates expiration after certificates updated364cert::check_master_certs_expiration365;;366all)367# check certificates expiration368cert::check_all_expiration369# backup $KUBE_PATH to $KUBE_PATH.old-$(date +%Y%m%d)370cert::backup_file "${KUBE_PATH}"371# update etcd certificates372log::info "${GREEN}updating...${NC}"373cert::update_etcd_cert374# update master certificates and kubeconf375cert::update_master_cert376log::info "${GREEN}done!!!${NC}"377# check certificates expiration after certificates updated378cert::check_all_expiration379;;380check)381# check certificates expiration382cert::check_all_expiration383;;384*)385log::err "unknown, unsupported cert type: ${node_type}, supported type: \"all\", \"master\""386printf "Documentation: https://github.com/yuyicai/update-kube-cert387example:388'\033[32m./update-kubeadm-cert.sh all\033[0m' update all etcd certificates, master certificates and kubeconf389/etc/kubernetes390├── admin.conf391├── controller-manager.conf392├── scheduler.conf393├── kubelet.conf394└── pki395├── apiserver.crt396├── apiserver-etcd-client.crt397├── apiserver-kubelet-client.crt398├── front-proxy-client.crt399└── etcd400├── healthcheck-client.crt401├── peer.crt402└── server.crt403404'\033[32m./update-kubeadm-cert.sh master\033[0m' update only master certificates and kubeconf405/etc/kubernetes406├── admin.conf407├── controller-manager.conf408├── scheduler.conf409├── kubelet.conf410└── pki411├── apiserver.crt412├── apiserver-kubelet-client.crt413└── front-proxy-client.crt414"415exit 1416;;417esac418}419420main "$@" - 업데이트 전 인증서 정보 확인
1
$> kubeadm certs check-expiration2[check-expiration] Reading configuration from the cluster...3[check-expiration] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'45CERTIFICATE EXPIRES RESIDUAL TIME CERTIFICATE AUTHORITY EXTERNALLY MANAGED6admin.conf Apr 17, 2023 06:09 UTC 364d ca no7apiserver Apr 17, 2023 06:09 UTC 364d ca no8apiserver-etcd-client Apr 17, 2023 06:09 UTC 364d etcd-ca no9apiserver-kubelet-client Apr 17, 2023 06:09 UTC 364d ca no10controller-manager.conf Apr 17, 2023 06:09 UTC 364d ca no11etcd-healthcheck-client Apr 17, 2023 06:09 UTC 364d etcd-ca no12etcd-peer Apr 17, 2023 06:09 UTC 364d etcd-ca no13etcd-server Apr 17, 2023 06:09 UTC 364d etcd-ca no14front-proxy-client Apr 17, 2023 06:09 UTC 364d front-proxy-ca no15scheduler.conf Apr 17, 2023 06:09 UTC 364d ca no1617CERTIFICATE AUTHORITY EXPIRES RESIDUAL TIME EXTERNALLY MANAGED18ca Apr 17, 2032 04:17 UTC 9y no19etcd-ca Apr 17, 2032 04:17 UTC 9y no20front-proxy-ca Apr 17, 2032 04:17 UTC 9y no - 인증서 업데이트 (Control Plain 1대씩 순차 작업 수행, 서버단위로 30초 가량 대기 필요)
1
$> chmod +x cert_update.sh2$> ./cert_update.sh3... - 인증서 갱신정보 확인
1
$> kubeadm certs check-expiration2[check-expiration] Reading configuration from the cluster...3[check-expiration] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'45CERTIFICATE EXPIRES RESIDUAL TIME CERTIFICATE AUTHORITY EXTERNALLY MANAGED6admin.conf Apr 17, 2032 06:09 UTC 9y ca no7apiserver Apr 17, 2032 06:09 UTC 9y ca no8apiserver-etcd-client Apr 17, 2032 06:09 UTC 9y etcd-ca no9apiserver-kubelet-client Apr 17, 2032 06:09 UTC 9y ca no10controller-manager.conf Apr 17, 2032 06:09 UTC 9y ca no11etcd-healthcheck-client Apr 17, 2032 06:09 UTC 9y etcd-ca no12etcd-peer Apr 17, 2032 06:09 UTC 9y etcd-ca no13etcd-server Apr 17, 2032 06:09 UTC 9y etcd-ca no14front-proxy-client Apr 17, 2032 06:09 UTC 9y front-proxy-ca no15scheduler.conf Apr 17, 2032 06:09 UTC 9y ca no1617CERTIFICATE AUTHORITY EXPIRES RESIDUAL TIME EXTERNALLY MANAGED18ca Apr 17, 2032 04:17 UTC 9y no19etcd-ca Apr 17, 2032 04:17 UTC 9y no20front-proxy-ca Apr 17, 2032 04:17 UTC 9y no
Reference
728x90
반응형