antony@notes:~/rancher$ cat "Rancher-API-Create-K3s-Cluster.md"
Rancher API Create K3s Cluster
Rancher API Create K3s Cluster
1. 先決要求
- 已完成安裝 Rancher v2.10.1
- 一台剛安裝好 Linux 作業系統的電腦
bash、curl、jq和yq命令須先完成安裝
2. 開始實作
在 Rancher UI 建立 token
將
ACCESS_KEY、SECRET_KEY和Rancher_URL設為變數
export CATTLE_ACCESS_KEY='token-vr4rr'
export CATTLE_SECRET_KEY='4sqjmbxx47k2pd286gkrvd27wmfpvs599htqnxhqnpv5kqwb74r49f'
export Rancher_URL='antony-rancher.example.com'
export Cluster_Name='test'- 撰寫 K3s 叢集設定檔
cat << EOF > ${HOME}/k3s.yaml
apiVersion: provisioning.cattle.io/v1
kind: Cluster
metadata:
name: ${Cluster_Name}
namespace: fleet-default
spec:
kubernetesVersion: v1.31.3+k3s1
rkeConfig:
machineGlobalConfig:
cluster-cidr: 172.99.0.0/16
cluster-dns: 172.100.10.10
disable:
- servicelb
- traefik
kube-apiserver-arg:
- '--default-not-ready-toleration-seconds=5'
- '--default-unreachable-toleration-seconds=5'
kube-controller-manager-arg:
- '--node-monitor-grace-period=20s'
service-cidr: 172.100.0.0/16
tls-san:
- 127.0.0.1
- 192.168.11.150
- 192.168.11.21
disable-network-policy: true
secrets-encryption: false
machineSelectorConfig:
- config:
kubelet-arg:
- container-log-max-files=5
- container-log-max-size=10Mi
selinux: true
__clone: true
EOF- 使用 yq 工具將 k3s 叢集設定檔轉換成 json 格式
yq eval -o=json ${HOME}/k3s.yaml > ${HOME}/k3s.json- 呼叫 Rancher 建立 K3s
curl -k -u "${CATTLE_ACCESS_KEY}:${CATTLE_SECRET_KEY}" \
-X POST \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d @${HOME}/k3s.json \
https://${Rancher_URL}/v1/provisioning.cattle.io.clusters- 將新建立 K3s 叢集的
clusterid設為變數
export ClusterID=$(curl -s -k -u "${CATTLE_ACCESS_KEY}:${CATTLE_SECRET_KEY}" \
-H 'Accept: application/json' \
https://${Rancher_URL}/v3/clusters | \
jq -r ".data[] | select(.name == \"${Cluster_Name}\") | .id")- 獲取同時具有 etcd、controlplane 和 worker Role 的註冊指令
CODE=$(curl -s -k -u "${CATTLE_ACCESS_KEY}:${CATTLE_SECRET_KEY}" \
https://${Rancher_URL}/v3/clusters/${ClusterID}/clusterregistrationtokens | \
jq -r .data[].insecureNodeCommand)
echo "$CODE --etcd --controlplane --worker"執行結果應與以下類似 :
curl --insecure -fL https://antony-rancher.example.com/system-agent-install.sh | sudo sh -s - --server https://antony-rancher.example.com --label 'cattle.io/os=linux' --token mckc626z5tsvzs8z2rv7lkk8hpctl4z6rw5hfb66qb4cc8h24fsr6f --ca-checksum de987cd6d56600459cbbb895564eaf04687d2dedeeab39cf7c83ef761dc93332 --etcd --controlplane --worker