Last active
July 9, 2026 00:05
-
-
Save masezou/65c29fcff3a761335506b908f97228a3 to your computer and use it in GitHub Desktop.
k3s setup for Ubuntu Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # Copyright (c) 2025 masezou. All rights reserved. | |
| ######################################################### | |
| BASEDOMAIN="${BASEDOMAIN:-sslip.io}" | |
| exec > >(tee -a /var/log/k3s-setup.log) 2>&1 | |
| bold_msg() { | |
| echo -e "\033[1m$1\033[0m" | |
| } | |
| bold_green_msg() { | |
| echo -e "\033[1m\033[32m$1\033[0m" | |
| } | |
| green_msg() { | |
| echo -e "\033[1;32m$1\033[0m" | |
| } | |
| red_msg() { | |
| echo -e "\033[1;31m$1\033[0m" | |
| } | |
| yellow_msg() { | |
| echo -e "\033[1;33m$1\033[0m" | |
| } | |
| all_checks_passed=true | |
| bold_msg "Checking Environment: WSL or Physical" | |
| WSL_VERSION="not-wsl" | |
| PHYSICAL=1 | |
| if grep -qEi "(microsoft|wsl)" /proc/version; then | |
| if grep -q "microsoft-standard" /proc/sys/kernel/osrelease; then | |
| WSL_VERSION="wsl2" | |
| PHYSICAL=0 | |
| yellow_msg "Running on WSL2: PHYSICAL=$PHYSICAL" | |
| else | |
| WSL_VERSION="wsl1" | |
| red_msg "WSL1 detected. This environment is not supported. Exiting..." | |
| exit 1 | |
| fi | |
| else | |
| green_msg "Physical or Virtual Machine environment detected: PHYSICAL=$PHYSICAL" | |
| fi | |
| # Architecture | |
| ARCH=$(dpkg --print-architecture) | |
| bold_msg "Checking Architecture: Required (amd64 or arm64), Current ($ARCH)" | |
| if [[ "$ARCH" == "amd64" || "$ARCH" == "arm64" ]]; then | |
| green_msg "Architecture ($ARCH) OK" | |
| else | |
| red_msg "Architecture ($ARCH) NG" | |
| all_checks_passed=false | |
| fi | |
| # Ubuntu version | |
| ubuntu_version=$(lsb_release -rs) | |
| bold_msg "Checking Ubuntu Version: Required (24.04 or 26.04), Current ($ubuntu_version)" | |
| if [[ "$ubuntu_version" == "24.04" || "$ubuntu_version" == "26.04" ]]; then | |
| green_msg "Ubuntu Version ($ubuntu_version) OK" | |
| else | |
| red_msg "Ubuntu Version ($ubuntu_version) NG" | |
| all_checks_passed=false | |
| fi | |
| # Server/Desktop check | |
| description=$(lsb_release -d | cut -f2) | |
| desktop_check=$(echo "$description" | grep -i "desktop") | |
| bold_msg "Checking Server Edition: Required (Server), Current ($description)" | |
| if [[ -z "$desktop_check" ]]; then | |
| green_msg "Edition (Server) OK" | |
| else | |
| red_msg "Edition (Desktop) NG" | |
| all_checks_passed=false | |
| fi | |
| # CPU cores | |
| cpu_cores=$(nproc) | |
| bold_msg "Checking CPU Cores: Required (4 or more), Current ($cpu_cores)" | |
| if [[ "$cpu_cores" -ge 4 ]]; then | |
| green_msg "CPU Cores ($cpu_cores) OK" | |
| else | |
| red_msg "CPU Cores ($cpu_cores) NG" | |
| all_checks_passed=false | |
| fi | |
| # CPU virtualization availability | |
| if grep -qwE 'vmx|svm' /proc/cpuinfo; then | |
| green_msg "CPU Virtualization Support (vmx/svm) OK. kubevirt will be installed" | |
| KUBEVIRT=1 | |
| else | |
| red_msg "CPU Virtualization Support (vmx/svm) NG: Not found in /proc/cpuinfo" | |
| KUBEVIRT=0 | |
| fi | |
| # Memory (rounded GB) | |
| mem_total_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}') | |
| mem_total_gb=$(awk "BEGIN { printf \"%.0f\", $mem_total_kb / 1024 / 1024 }") | |
| bold_msg "Checking Memory: Required (8GB or more), Current (${mem_total_gb}GB)" | |
| if [[ "$mem_total_gb" -ge 8 ]]; then | |
| green_msg "Memory (${mem_total_gb}GB) OK" | |
| else | |
| red_msg "Memory (${mem_total_gb}GB) NG" | |
| all_checks_passed=false | |
| fi | |
| # Disk space | |
| disk_free_gb=$(df --output=avail / | tail -n 1 | awk '{printf "%.0f", $1 / 1024 / 1024}') | |
| bold_msg "Checking Disk Space: Required (50GB or more), Current (${disk_free_gb}GB)" | |
| if [[ "$disk_free_gb" -ge 50 ]]; then | |
| green_msg "Disk Space (${disk_free_gb}GB) OK" | |
| else | |
| red_msg "Disk Space (${disk_free_gb}GB) NG" | |
| all_checks_passed=false | |
| fi | |
| # Final result | |
| if $all_checks_passed; then | |
| bold_green_msg "All checks passed. Continue..." | |
| else | |
| red_msg "Some checks failed. Please fix the issues and retry." | |
| exit 1 | |
| fi | |
| bold_green_msg "pre-setup" | |
| apt -y update ; apt -y upgrade | |
| tee /etc/sysctl.d/10-k8s.conf << EOF | |
| fs.inotify.max_user_instances = 1024 | |
| fs.inotify.max_user_watches = 1048576 | |
| EOF | |
| sysctl -p /etc/sysctl.d/10-k8s.conf | |
| sysctl -a | grep "fs.inotify" | |
| swapoff -a | |
| sed -i '/swap/s/^/#/' /etc/fstab | |
| # Report only actual ip address from VMware Tools | |
| if [ -d /etc/vmware-tools ]; then | |
| cat <<EOF >/etc/vmware-tools/tools.conf.tmp | |
| [guestinfo] | |
| exclude-nics=cni*,flannel*,podman*,lxdbr*,veth*,docker*,virbr*,br-*,lxc*,cilium*,vxlan*,calico*,cali* | |
| EOF | |
| cp /etc/vmware-tools/tools.conf /etc/vmware-tools/tools.conf.orig | |
| cat /etc/vmware-tools/tools.conf.tmp /etc/vmware-tools/tools.conf.orig >/etc/vmware-tools/tools.conf | |
| rm /etc/vmware-tools/tools.conf.tmp | |
| apt -y install open-vm-tools-containerinfo | |
| systemctl stop open-vm-tools.service | |
| systemctl start open-vm-tools.service | |
| fi | |
| bold_green_msg "Install local registry" | |
| REGDIR=/disk/registry | |
| mkdir -p ${REGDIR} | |
| ln -s ${REGDIR} /var/lib/docker-registry | |
| ufw allow 5000 | |
| apt -y install docker-registry | |
| sed -i -e "s/ htpasswd/# htpasswd/g" /etc/docker/registry/config.yml | |
| sed -i -e "s/ realm/# realm/g" /etc/docker/registry/config.yml | |
| sed -i -e "s/ path/# path/g" /etc/docker/registry/config.yml | |
| cat <<EOF >/etc/cron.hourly/docker-registry-garbage | |
| #!/bin/sh | |
| /usr/bin/docker-registry garbage-collect /etc/docker/registry/config.yml | |
| EOF | |
| chmod +x /etc/cron.hourly/docker-registry-garbage | |
| systemctl restart docker-registry | |
| systemctl enable docker-registry | |
| LOCALIPADDR=$(ip -4 -o addr show dev "$(ip route | awk '/^default/ {for(i=1;i<=NF;i++) if ($i=="dev") print $(i+1); exit}')" | awk '{print $4}' | cut -d/ -f1) | |
| REGISTRYHOST=${LOCALIPADDR} | |
| REGISTRYPORT=5000 | |
| REGISTRY=${REGISTRYHOST}:${REGISTRYPORT} | |
| REGISTRYURL=http://${REGISTRY} | |
| bold_green_msg "Install reg for registry" | |
| curl -Lo reg https://github.com/genuinetools/reg/releases/download/v0.16.1/reg-linux-${ARCH} | |
| chmod +x reg | |
| mv reg /usr/local/bin/ | |
| reg ls -f ${REGISTRYURL} | |
| bold_green_msg "Install k3s" | |
| apt -y install curl iptables ipset conntrack kmod apparmor | |
| curl -sfL https://get.k3s.io | INSTALL_K3S_CHANNEL=v1.36 K3S_KUBECONFIG_MODE="644" sh - | |
| sleep 20 | |
| kubectl -n kube-system wait pod -l k8s-app=kube-dns --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l k8s-app=metrics-server --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l app=local-path-provisioner --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l svccontroller.k3s.cattle.io/svcnamespace=kube-system --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l app.kubernetes.io/instance=traefik-kube-system --for condition=Ready --timeout 60s | |
| kubectl label node `hostname` node-role.kubernetes.io/worker=worker | |
| cat <<EOF >/etc/rancher/k3s/registries.yaml | |
| mirrors: | |
| "${REGISTRY}": | |
| endpoint: | |
| - "${REGISTRYURL}" | |
| EOF | |
| systemctl restart k3s | |
| sleep 30 | |
| kubectl -n kube-system wait pod -l k8s-app=kube-dns --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l k8s-app=metrics-server --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l app=local-path-provisioner --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l svccontroller.k3s.cattle.io/svcnamespace=kube-system --for condition=Ready --timeout 60s | |
| kubectl -n kube-system wait pod -l app.kubernetes.io/instance=traefik-kube-system --for condition=Ready --timeout 60s | |
| k3s check-config | |
| mkdir -p ~/.kube | |
| cp /etc/rancher/k3s/k3s.yaml ~/.kube/config | |
| PUBLICIP=`kubectl get nodes -o jsonpath='{.items[*].metadata.annotations.flannel\.alpha\.coreos\.com\/public-ip}'` | |
| sed -i -e "s/127.0.0.1/${PUBLICIP}/g" ~/.kube/config | |
| chmod 400 ~/.kube/config | |
| PUBLICIP_HYPHENATED=$(printf "%s" "$PUBLICIP" | tr '.' '-') | |
| LOWERCASE_HOSTNAME=$(hostname | tr '[:upper:]' '[:lower:]') | |
| DNSDOMAINNAME="${LOWERCASE_HOSTNAME}.${PUBLICIP_HYPHENATED}.${BASEDOMAIN}" | |
| cat <<EOF | sudo tee /etc/profile.d/k3s-env.sh >/dev/null | |
| #!/bin/sh | |
| # Default wildcard DNS domain | |
| export BASEDOMAIN="${BASEDOMAIN}" | |
| # Export DNSDOMAINNAME for Kubernetes lab environment | |
| if command -v kubectl >/dev/null 2>&1; then | |
| PUBLICIP=\$(kubectl get nodes \ | |
| -o jsonpath='{.items[0].metadata.annotations.flannel\.alpha\.coreos\.com\/public-ip}' \ | |
| 2>/dev/null) | |
| if [ -n "\$PUBLICIP" ]; then | |
| PUBLICIP_HYPHENATED=\$(printf "%s" "\$PUBLICIP" | tr '.' '-') | |
| LOWERCASE_HOSTNAME=\$(hostname | tr '[:upper:]' '[:lower:]') | |
| export PUBLICIP | |
| export PUBLICIP_HYPHENATED | |
| export LOWERCASE_HOSTNAME | |
| export DNSDOMAINNAME="\${LOWERCASE_HOSTNAME}.\${PUBLICIP_HYPHENATED}.\${BASEDOMAIN}" | |
| fi | |
| fi | |
| EOF | |
| sudo chmod 644 /etc/profile.d/k3s-env.sh | |
| kubectl config rename-context default ${LOWERCASE_HOSTNAME}-cluster | |
| apt -y install bash-completion | |
| k3s completion bash > /etc/bash_completion.d/k3s | |
| source /etc/bash_completion.d/k3s | |
| kubectl completion bash > /etc/bash_completion.d/kubectl | |
| source /etc/bash_completion.d/kubectl | |
| crictl completion bash > /etc/bash_completion.d/crictl | |
| source /etc/bash_completion.d/crictl | |
| CONTAINERDVER=$(kubectl get node -o wide | grep -o 'containerd://[0-9.]*' | sed 's/containerd:\/\///' | sort -u | head -n1) | |
| curl --retry 10 --retry-delay 3 --retry-connrefused -sS https://raw.githubusercontent.com/containerd/containerd/refs/tags/v${CONTAINERDVER}/contrib/autocomplete/ctr -o /etc/bash_completion.d/ctr | |
| source /etc/bash_completion.d/ctr | |
| for udir in /home/*; do | |
| [ -d "$udir" ] || continue | |
| user=$(basename "$udir") | |
| mkdir -p "$udir/.kube" | |
| cp /root/.kube/config "$udir/.kube/config" | |
| chown -R "$user:$user" "$udir/.kube" | |
| chmod 400 "$udir/.kube/config" | |
| done | |
| bold_green_msg "Install helm" | |
| if type "helm" >/dev/null 2>&1; then | |
| echo -e "\e[32mhelm OK. \e[m" | |
| else | |
| apt install -y curl gpg apt-transport-https | |
| curl -fsSL https://packages.buildkite.com/helm-linux/helm-debian/gpgkey | gpg --dearmor -o /usr/share/keyrings/helm.gpg | |
| echo 'deb [signed-by=/usr/share/keyrings/helm.gpg] https://packages.buildkite.com/helm-linux/helm-debian/any/ any main' | tee /etc/apt/sources.list.d/helm-stable-debian.list >/dev/null | |
| apt update | |
| apt -y install helm | |
| #curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | |
| #chmod 700 get_helm.sh | |
| #./get_helm.sh | |
| fi | |
| helm version | |
| helm completion bash >/etc/bash_completion.d/helm | |
| source /etc/bash_completion.d/helm | |
| bold_green_msg "Install radar dashboard" | |
| cat <<EOF > radar-values.yaml | |
| ingress: | |
| enabled: true | |
| className: traefik | |
| hosts: | |
| - host: radar.${DNSDOMAINNAME} | |
| paths: | |
| - path: / | |
| pathType: Prefix | |
| EOF | |
| helm repo add skyhook https://skyhook-io.github.io/helm-charts | |
| helm repo update | |
| helm upgrade --install radar skyhook/radar \ | |
| -n radar \ | |
| --create-namespace \ | |
| -f radar-values.yaml | |
| kubectl apply -f - <<'EOF' | |
| apiVersion: rbac.authorization.k8s.io/v1 | |
| kind: ClusterRole | |
| metadata: | |
| name: radar-readonly | |
| rules: | |
| - apiGroups: ["", "apps", "batch", "extensions", "networking.k8s.io", "autoscaling"] | |
| resources: ["*"] | |
| verbs: ["get", "list", "watch"] | |
| - apiGroups: [""] | |
| resources: ["secrets", "configmaps"] | |
| verbs: ["get", "list", "watch"] | |
| - apiGroups: ["apiextensions.k8s.io"] | |
| resources: ["customresourcedefinitions"] | |
| verbs: ["get", "list", "watch"] | |
| --- | |
| apiVersion: rbac.authorization.k8s.io/v1 | |
| kind: ClusterRoleBinding | |
| metadata: | |
| name: radar-readonly | |
| subjects: | |
| - kind: ServiceAccount | |
| name: radar | |
| namespace: radar | |
| roleRef: | |
| apiGroup: rbac.authorization.k8s.io | |
| kind: ClusterRole | |
| name: radar-readonly | |
| EOF | |
| kubectl create clusterrolebinding radar-cluster-admin \ | |
| --clusterrole=cluster-admin \ | |
| --serviceaccount=radar:radar | |
| helm repo add groundcover https://helm.groundcover.com | |
| helm repo update groundcover | |
| helm upgrade --install caretta groundcover/caretta \ | |
| -n caretta \ | |
| --create-namespace \ | |
| --set resources.limits.memory=512Mi | |
| kubectl rollout restart deployment/radar -n radar | |
| bold_green_msg "Deploy local registry frontend" | |
| ctr images pull --platform linux/${ARCH} docker.io/ekazakov/docker-registry-frontend:latest | |
| ctr images tag docker.io/ekazakov/docker-registry-frontend:latest ${REGISTRY}/docker-registry-frontend:latest | |
| ctr images push --platform linux/${ARCH} --plain-http ${REGISTRY}/docker-registry-frontend:latest | |
| ctr images rm docker.io/ekazakov/docker-registry-frontend:latest | |
| ctr images rm ${REGISTRY}/docker-registry-frontend:latest | |
| reg tags -f ${REGISTRY}/docker-registry-frontend | |
| kubectl create ns registryfe | |
| cat <<EOF | kubectl apply -n registryfe -f - | |
| apiVersion: apps/v1 | |
| kind: Deployment | |
| metadata: | |
| name: registryfe | |
| spec: | |
| replicas: 1 | |
| selector: | |
| matchLabels: | |
| app: registryfe | |
| template: | |
| metadata: | |
| labels: | |
| app: registryfe | |
| spec: | |
| containers: | |
| - name: registryfe | |
| image: ${REGISTRY}/docker-registry-frontend:latest | |
| env: | |
| - name: ENV_DOCKER_REGISTRY_HOST | |
| value: "${REGISTRYHOST}" | |
| - name: ENV_DOCKER_REGISTRY_PORT | |
| value: "${REGISTRYPORT}" | |
| ports: | |
| - containerPort: 80 | |
| name: http | |
| EOF | |
| cat <<EOF | kubectl apply -n registryfe -f - | |
| apiVersion: v1 | |
| kind: Service | |
| metadata: | |
| name: registryfe | |
| spec: | |
| selector: | |
| app: registryfe | |
| ports: | |
| - protocol: TCP | |
| port: 80 | |
| targetPort: 80 | |
| nodePort: 30000 | |
| type: NodePort | |
| EOF | |
| kubectl -n registryfe get all | |
| if [[ "$PHYSICAL" -eq 1 ]]; then | |
| bold_green_msg "Install External snapshotter" | |
| SNAPSHOTTERVER=8.5.0 | |
| # Apply VolumeSnapshot CRDs | |
| kubectl create -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v${SNAPSHOTTERVER}/client/config/crd/snapshot.storage.k8s.io_volumesnapshotclasses.yaml | |
| kubectl create -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v${SNAPSHOTTERVER}/client/config/crd/snapshot.storage.k8s.io_volumesnapshotcontents.yaml | |
| kubectl create -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v${SNAPSHOTTERVER}/client/config/crd/snapshot.storage.k8s.io_volumesnapshots.yaml | |
| # Create Snapshot Controller | |
| curl --retry 10 --retry-delay 3 --retry-connrefused -sSOL https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v${SNAPSHOTTERVER}/deploy/kubernetes/snapshot-controller/rbac-snapshot-controller.yaml | |
| sed -i -e "s/namespace: default/namespace: kube-system/g" rbac-snapshot-controller.yaml | |
| kubectl create -f rbac-snapshot-controller.yaml | |
| rm -rf rbac-snapshot-controller.yaml | |
| curl --retry 10 --retry-delay 3 --retry-connrefused -sSOL https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v${SNAPSHOTTERVER}/deploy/kubernetes/snapshot-controller/setup-snapshot-controller.yaml | |
| sed -i -e "s/namespace: default/namespace: kube-system/g" setup-snapshot-controller.yaml | |
| kubectl create -f setup-snapshot-controller.yaml | |
| rm -rf setup-snapshot-controller.yaml | |
| kubectl -n kube-system wait pod -l app.kubernetes.io/name=snapshot-controller --for condition=Ready --timeout 60s | |
| bold_green_msg "Install Longhorn (Prepare)" | |
| apt -y install nfs-common jq open-iscsi cryptsetup dmsetup | |
| # Load NFS kernel module for Longhorn RWX support. | |
| modprobe nfs || true | |
| modprobe nfsv4 || true | |
| # Persist NFS modules across reboot. | |
| cat >/etc/modules-load.d/longhorn-nfs.conf <<'EOM' | |
| nfs | |
| nfsv4 | |
| EOM | |
| systemctl stop multipathd.socket && systemctl disable multipathd.socket | |
| systemctl stop multipathd && systemctl disable multipathd | |
| modprobe iscsi_tcp | |
| modprobe dm_crypt | |
| echo "iscsi_tcp" > /etc/modules-load.d/iscsi_tcp.conf | |
| echo "dm_crypt" > /etc/modules-load.d/dm_crypt.conf | |
| sed -i -e "s/debian/debian.$(hostname)/g" /etc/iscsi/initiatorname.iscsi | |
| systemctl restart iscsid.service | |
| bold_green_msg "Install Longhorn" | |
| kubectl -n kube-system scale deployment coredns --replicas=2 | |
| LONGHORNVER=1.12.0 | |
| curl -sSfL -o longhornctl https://github.com/longhorn/cli/releases/download/v${LONGHORNVER}/longhornctl-linux-${ARCH} | |
| chmod +x ./longhornctl | |
| kubectl create ns longhorn-system | |
| ./longhornctl check preflight --kubeconfig=/etc/rancher/k3s/k3s.yaml | |
| helm repo add longhorn https://charts.longhorn.io | |
| helm repo update | |
| helm install longhorn longhorn/longhorn --namespace longhorn-system --set persistence.defaultClassReplicaCount=1 --set-string defaultSettings.defaultReplicaCount=1 --set defaultSettings.replicaZoneSoftAntiAffinity=true --set longhornUI.replicas=1 --set ingress.enabled=true --set ingress.host=longhorn.${DNSDOMAINNAME} --version $LONGHORNVER --wait | |
| sleep 60 | |
| kubectl -n longhorn-system wait pod -l app=csi-attacher --for condition=Ready --timeout 300s | |
| kubectl -n longhorn-system wait pod -l app=csi-provisioner --for condition=Ready --timeout 300s | |
| kubectl -n longhorn-system wait pod -l app=csi-resizer --for condition=Ready --timeout 300s | |
| kubectl -n longhorn-system wait pod -l app=csi-snapshotter --for condition=Ready --timeout 300s | |
| kubectl label node `cat /etc/hostname` topology.kubernetes.io/zone=`cat /etc/hostname` | |
| cat <<EOF | kubectl apply -f - | |
| kind: VolumeSnapshotClass | |
| apiVersion: snapshot.storage.k8s.io/v1 | |
| metadata: | |
| annotations: | |
| snapshot.storage.kubernetes.io/is-default-class: "true" | |
| name: longhorn-snapshot-vsc | |
| driver: driver.longhorn.io | |
| deletionPolicy: Delete | |
| parameters: | |
| type: snap | |
| EOF | |
| kubectl get volumesnapshotclasses | |
| cp /var/lib/rancher/k3s/server/manifests/local-storage.yaml /var/lib/rancher/k3s/server/manifests/custom-local-storage.yaml | |
| sed -i -e "s/storageclass.kubernetes.io\/is-default-class: \"true\"/storageclass.kubernetes.io\/is-default-class: \"false\"/g" /var/lib/rancher/k3s/server/manifests/custom-local-storage.yaml | |
| #kubectl patch storageclass local-path -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}' | |
| sleep 20 | |
| kubectl get sc | |
| bold_green_msg "Setup kubevirt. It will take 3-5 min at least." | |
| if [[ "${KUBEVIRT:-0}" == "1" ]]; then | |
| KUBEVIRT_VERSION="v1.8.4" | |
| CDI_VERSION="v1.65.0" | |
| NAMESPACE="kubevirt" | |
| kubectl create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f - | |
| kubectl apply -n "$NAMESPACE" -f "https://github.com/kubevirt/kubevirt/releases/download/${KUBEVIRT_VERSION}/kubevirt-operator.yaml" | |
| kubectl apply -n "$NAMESPACE" -f "https://github.com/kubevirt/kubevirt/releases/download/${KUBEVIRT_VERSION}/kubevirt-cr.yaml" | |
| kubectl wait kv kubevirt -n "$NAMESPACE" --for condition=Available --timeout=300s | |
| kubectl create -f https://github.com/kubevirt/containerized-data-importer/releases/download/${CDI_VERSION}/cdi-operator.yaml | |
| kubectl create -f https://github.com/kubevirt/containerized-data-importer/releases/download/${CDI_VERSION}/cdi-cr.yaml | |
| kubectl wait deployment cdi-operator -n cdi --for condition=Available --timeout=300s | |
| for NODE in $(kubectl get nodes -l node-role.kubernetes.io/worker --no-headers -o custom-columns=":metadata.name"); do | |
| kubectl label node "$NODE" kubevirt.io/schedulable=true --overwrite | |
| done | |
| curl -LO https://github.com/kubevirt/kubevirt/releases/download/${KUBEVIRT_VERSION}/virtctl-${KUBEVIRT_VERSION}-linux-amd64 | |
| chmod +x virtctl-${KUBEVIRT_VERSION}-linux-amd64 | |
| mv virtctl-${KUBEVIRT_VERSION}-linux-amd64 /usr/local/bin/virtctl | |
| virtctl completion bash > /etc/bash_completion.d/virtctl | |
| source /etc/bash_completion.d/virtctl | |
| kubectl patch kubevirt kubevirt -n $NAMESPACE --type='merge' -p ' | |
| { | |
| "spec": { | |
| "configuration": { | |
| "developerConfiguration": { | |
| "featureGates": [ | |
| "VMExport" | |
| ] | |
| } | |
| } | |
| } | |
| }' | |
| fi | |
| cat > sample-ubuntu2604-vm.sh <<'SCRIPT' | |
| #!/usr/bin/env bash | |
| VM_NAMESPACE="kubevirt-ubuntu" | |
| VM_NAME="${VM_NAMESPACE}-vm" | |
| DISKSIZE="5Gi" | |
| [ -f ~/.ssh/id_ed25519 ] || ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N "" -C "$(whoami)@$(hostname)-$(date +%Y%m%d)" | |
| SSH_PUBLIC_KEY="$(cat ~/.ssh/id_ed25519.pub)" | |
| kubectl create ns "${VM_NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f - | |
| cat <<EOF | kubectl apply -n "${VM_NAMESPACE}" -f - | |
| apiVersion: cdi.kubevirt.io/v1beta1 | |
| kind: DataVolume | |
| metadata: | |
| name: ${VM_NAME}-dv | |
| spec: | |
| source: | |
| http: | |
| url: https://cloud-images.ubuntu.com/resolute/current/resolute-server-cloudimg-amd64v3.img | |
| pvc: | |
| accessModes: | |
| - ReadWriteOnce | |
| resources: | |
| requests: | |
| storage: ${DISKSIZE} | |
| storageClassName: longhorn | |
| volumeMode: Filesystem | |
| --- | |
| apiVersion: kubevirt.io/v1 | |
| kind: VirtualMachine | |
| metadata: | |
| name: ${VM_NAME} | |
| spec: | |
| runStrategy: Always | |
| template: | |
| metadata: | |
| labels: | |
| kubevirt.io/domain: ${VM_NAME} | |
| spec: | |
| domain: | |
| cpu: | |
| cores: 2 | |
| sockets: 1 | |
| threads: 1 | |
| model: host-passthrough | |
| resources: | |
| requests: | |
| memory: 2Gi | |
| cpu: "2" | |
| limits: | |
| memory: 2Gi | |
| cpu: "2" | |
| machine: | |
| type: q35 | |
| devices: | |
| disks: | |
| - name: rootdisk | |
| disk: | |
| bus: virtio | |
| - name: cloudinitdisk | |
| disk: | |
| bus: virtio | |
| terminationGracePeriodSeconds: 30 | |
| volumes: | |
| - name: rootdisk | |
| dataVolume: | |
| name: ${VM_NAME}-dv | |
| - name: cloudinitdisk | |
| cloudInitNoCloud: | |
| userData: | | |
| #cloud-config | |
| users: | |
| - name: ubuntu | |
| lock_passwd: false | |
| sudo: ALL=(ALL) NOPASSWD:ALL | |
| groups: sudo | |
| shell: /bin/bash | |
| ssh_authorized_keys: | |
| - ${SSH_PUBLIC_KEY} | |
| chpasswd: | |
| list: | | |
| ubuntu:ubuntu | |
| expire: false | |
| ssh_pwauth: true | |
| disable_root: true | |
| package_update: true | |
| package_upgrade: true | |
| packages: | |
| - openssh-server | |
| - qemu-guest-agent | |
| - vim | |
| runcmd: | |
| - systemctl enable --now ssh | |
| - systemctl enable --now qemu-guest-agent | |
| EOF | |
| echo "[+] Waiting for DataVolume to succeed..." | |
| for i in {1..60}; do | |
| kubectl get datavolume -n "${VM_NAMESPACE}" | |
| STATUS=$(kubectl get "dv/${VM_NAME}-dv" -n "${VM_NAMESPACE}" -o jsonpath='{.status.phase}' 2>/dev/null || echo "") | |
| if [[ "${STATUS}" == "Succeeded" ]]; then | |
| echo "[β] DataVolume is ready." | |
| break | |
| fi | |
| echo "[-] DataVolume status: ${STATUS} (waiting...)" | |
| sleep 5 | |
| if [[ "${i}" -eq 60 ]]; then | |
| echo "[β] Timeout waiting for DataVolume to succeed." | |
| exit 1 | |
| fi | |
| done | |
| echo "[+] Waiting for VirtualMachineInstance to be Running..." | |
| for i in {1..60}; do | |
| PHASE=$(kubectl get vmi "${VM_NAME}" -n "${VM_NAMESPACE}" -o jsonpath='{.status.phase}' 2>/dev/null || echo "") | |
| if [[ "${PHASE}" == "Running" ]]; then | |
| echo "[β] VirtualMachineInstance '${VM_NAME}' is running in namespace '${VM_NAMESPACE}'." | |
| echo "" | |
| echo "virtctl console ${VM_NAME} -n ${VM_NAMESPACE}" | |
| echo "username: ubuntu password: ubuntu" | |
| break | |
| fi | |
| echo "[-] Waiting for VM to become Running (current: ${PHASE})..." | |
| sleep 5 | |
| done | |
| # Wait for DataVolume to complete, with progress output | |
| echo "[+] Waiting for DataVolume to succeed..." | |
| for i in {1..60}; do | |
| kubectl get datavolume -n "$VM_NAMESPACE" | |
| STATUS=$(kubectl get dv/${VM_NAME}-dv -n "$VM_NAMESPACE" -o jsonpath='{.status.phase}' 2>/dev/null || echo "") | |
| if [[ "$STATUS" == "Succeeded" ]]; then | |
| echo "[β] DataVolume is ready." | |
| break | |
| fi | |
| echo "[-] DataVolume status: $STATUS (waiting...)" | |
| sleep 5 | |
| if [[ $i -eq 60 ]]; then | |
| echo "[β] Timeout waiting for DataVolume to succeed." | |
| exit 1 | |
| fi | |
| done | |
| # Wait for VirtualMachineInstance to be Running | |
| echo "[+] Waiting for VirtualMachineInstance to be Running..." | |
| for i in {1..60}; do | |
| PHASE=$(kubectl get vmi "$VM_NAME" -n "$VM_NAMESPACE" -o jsonpath='{.status.phase}' 2>/dev/null || echo "") | |
| if [[ "$PHASE" == "Running" ]]; then | |
| VMIP=$(kubectl -n "$VM_NAMESPACE" get vmi ${VM_NAME} -o jsonpath='{.status.interfaces[0].ipAddress}' ;echo) | |
| echo "[β] VirtualMachineInstance '${VM_NAME}' is running in namespace '${VM_NAMESPACE}'." | |
| echo "" | |
| echo "π‘ To connect to the console, run:" | |
| echo " virtctl console $VM_NAME -n $VM_NAMESPACE" | |
| echo " username: ubuntu password: ubuntu" | |
| echo "or" | |
| echo " ssh ubuntu@${VMIP}" | |
| echo "" | |
| break | |
| fi | |
| echo "[-] Waiting for VM to become Running (current: $PHASE)..." | |
| sleep 5 | |
| if [[ $i -eq 60 ]]; then | |
| echo "[β] Timeout waiting for VMI to be Running." | |
| exit 1 | |
| fi | |
| done | |
| SCRIPT | |
| chmod +x sample-ubuntu2604-vm.sh | |
| fi | |
| bold_green_msg "setup traefilk dashboard" | |
| cat << 'EOF' > /var/lib/rancher/k3s/server/manifests/traefik-config.yaml | |
| apiVersion: helm.cattle.io/v1 | |
| kind: HelmChartConfig | |
| metadata: | |
| name: traefik | |
| namespace: kube-system | |
| spec: | |
| valuesContent: |- | |
| ingressRoute: | |
| dashboard: | |
| enabled: true | |
| healthcheck: | |
| enabled: true | |
| entryPoints: ["traefik", "web", "websecure"] | |
| logs: | |
| access: | |
| enabled: true | |
| service: | |
| spec: | |
| externalTrafficPolicy: Local | |
| ports: | |
| traefik: | |
| port: 8080 | |
| expose: | |
| default: true | |
| mysql: | |
| expose: false | |
| #exposedPort: 3306 | |
| hostPort: 3306 | |
| port: 3306 | |
| protocol: TCP | |
| pgsql: | |
| expose: false | |
| #exposedPort: 5432 | |
| hostPort: 5432 | |
| port: 5432 | |
| protocol: TCP | |
| providers: | |
| kubernetesCRD: | |
| allowCrossNamespace: true | |
| EOF | |
| bold_green_msg "Docker CLI" | |
| curl -fsSL https://get.docker.com -o get-docker.sh | |
| sh get-docker.sh | |
| cat << EOF > /etc/docker/daemon.json | |
| {"insecure-registries": ["${REGISTRY}"]} | |
| EOF | |
| systemctl restart docker | |
| ###### Sanity Check Script | |
| cd | |
| cat << 'EOFXX' > test_storage_snapshot.sh | |
| #!/bin/bash | |
| set -euo pipefail | |
| NAMESPACE="sc-test" | |
| PVC_SIZE="1Gi" | |
| ACCESS_MODE="ReadWriteOnce" | |
| VOLUME_MODES=("Filesystem" "Block") | |
| STORAGE_CLASSES=("local-path" "longhorn" "longhorn-static") | |
| SNAPSHOT_CLASS="longhorn-snapshot-vsc" | |
| echo "π¦ Creating namespace: $NAMESPACE" | |
| kubectl create ns "$NAMESPACE" || true | |
| for SC in "${STORAGE_CLASSES[@]}"; do | |
| for VOLUME_MODE in "${VOLUME_MODES[@]}"; do | |
| echo -e "\nπ§ͺ Testing StorageClass: $SC with volumeMode: $VOLUME_MODE" | |
| # Skip Block mode for non-Longhorn SCs | |
| if [[ "$VOLUME_MODE" == "Block" && "$SC" != longhorn* ]]; then | |
| echo "β οΈ Skipping Block mode test for non-Longhorn StorageClass: $SC" | |
| continue | |
| fi | |
| NAME=$(echo "${SC}-${VOLUME_MODE}" | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9' '-' | sed 's/^-*//; s/-*$//') | |
| PVC_NAME="pvc-${NAME}" | |
| POD_NAME="pod-${NAME}" | |
| SNAP_NAME="snap-${NAME}" | |
| echo "π§ Creating PVC: $PVC_NAME" | |
| cat <<EOF | kubectl apply -n "$NAMESPACE" -f - | |
| apiVersion: v1 | |
| kind: PersistentVolumeClaim | |
| metadata: | |
| name: $PVC_NAME | |
| spec: | |
| accessModes: | |
| - ${ACCESS_MODE} | |
| resources: | |
| requests: | |
| storage: ${PVC_SIZE} | |
| storageClassName: ${SC} | |
| volumeMode: ${VOLUME_MODE} | |
| EOF | |
| echo "π PVC created:" | |
| kubectl get pvc "$PVC_NAME" -n "$NAMESPACE" | |
| echo "π Creating Pod $POD_NAME using volumeMode: $VOLUME_MODE" | |
| if [[ "$VOLUME_MODE" == "Filesystem" ]]; then | |
| CMD="echo 'Hello from $SC-$VOLUME_MODE' > /mnt/testfile && sleep 3600" | |
| MOUNT_CONFIG=" | |
| volumeMounts: | |
| - mountPath: /mnt | |
| name: test-volume" | |
| else | |
| CMD="dd if=/dev/zero of=/dev/xvda bs=1M count=10 && sleep 3600" | |
| MOUNT_CONFIG=" | |
| volumeDevices: | |
| - devicePath: /dev/xvda | |
| name: test-volume" | |
| fi | |
| cat <<EOF | kubectl apply -n "$NAMESPACE" -f - | |
| apiVersion: v1 | |
| kind: Pod | |
| metadata: | |
| name: $POD_NAME | |
| spec: | |
| containers: | |
| - name: test-container | |
| image: busybox | |
| command: ["sh", "-c", "$CMD"]$MOUNT_CONFIG | |
| volumes: | |
| - name: test-volume | |
| persistentVolumeClaim: | |
| claimName: $PVC_NAME | |
| restartPolicy: Never | |
| EOF | |
| echo "β Waiting for Pod $POD_NAME to be Ready..." | |
| kubectl wait --for=condition=Ready pod/"$POD_NAME" -n "$NAMESPACE" --timeout=120s | |
| echo "π Pod created:" | |
| kubectl get pod "$POD_NAME" -n "$NAMESPACE" | |
| if [[ "$VOLUME_MODE" == "Filesystem" ]]; then | |
| echo "π Verifying written data..." | |
| OUTPUT=$(kubectl exec -n "$NAMESPACE" "$POD_NAME" -- cat /mnt/testfile) | |
| echo "π Read content: $OUTPUT" | |
| if [[ "$OUTPUT" != "Hello from $SC-$VOLUME_MODE" ]]; then | |
| echo "β Data verification failed for $SC-$VOLUME_MODE" | |
| continue | |
| fi | |
| fi | |
| if [[ "$SC" == longhorn* ]]; then | |
| echo "πΈ Creating VolumeSnapshot: $SNAP_NAME" | |
| cat <<EOF | kubectl apply -n "$NAMESPACE" -f - | |
| apiVersion: snapshot.storage.k8s.io/v1 | |
| kind: VolumeSnapshot | |
| metadata: | |
| name: $SNAP_NAME | |
| spec: | |
| volumeSnapshotClassName: $SNAPSHOT_CLASS | |
| source: | |
| persistentVolumeClaimName: $PVC_NAME | |
| EOF | |
| echo "β Waiting for VolumeSnapshot to be ready..." | |
| kubectl wait --for=jsonpath='{.status.readyToUse}'=true -n "$NAMESPACE" volumesnapshot/"$SNAP_NAME" --timeout=120s | |
| echo "π VolumeSnapshot created:" | |
| kubectl get volumesnapshot "$SNAP_NAME" -n "$NAMESPACE" | |
| else | |
| echo "β οΈ No snapshot test for $SC-$VOLUME_MODE" | |
| fi | |
| echo "π§Ή Cleaning up resources for $SC-$VOLUME_MODE" | |
| echo "π Deleting Pod:" | |
| kubectl get pod "$POD_NAME" -n "$NAMESPACE" || true | |
| kubectl delete pod "$POD_NAME" -n "$NAMESPACE" --wait | |
| echo "π Deleting PVC:" | |
| kubectl get pvc "$PVC_NAME" -n "$NAMESPACE" || true | |
| kubectl delete pvc "$PVC_NAME" -n "$NAMESPACE" --wait | |
| if kubectl get volumesnapshot "$SNAP_NAME" -n "$NAMESPACE" &>/dev/null; then | |
| echo "π Deleting VolumeSnapshot:" | |
| kubectl get volumesnapshot "$SNAP_NAME" -n "$NAMESPACE" | |
| kubectl delete volumesnapshot "$SNAP_NAME" -n "$NAMESPACE" --wait | |
| fi | |
| echo "β Completed test for StorageClass: $SC with volumeMode: $VOLUME_MODE" | |
| done | |
| done | |
| echo "π§½ Deleting namespace: $NAMESPACE" | |
| kubectl delete ns "$NAMESPACE" --wait | |
| echo -e "\nπ All StorageClass and volumeMode tests completed successfully" | |
| EOFXX | |
| chmod +x test_storage_snapshot.sh | |
| KUBECOLORVER=0.6.0 | |
| curl -OL https://github.com/kubecolor/kubecolor/releases/download/v${KUBECOLORVER}/kubecolor_${KUBECOLORVER}_linux_${ARCH}.tar.gz | |
| tar xfz kubecolor_${KUBECOLORVER}_linux_${ARCH}.tar.gz | |
| rm -rf LICENSE README.md kubecolor_${KUBECOLORVER}_linux_${ARCH}.tar.gz /usr/local/bin/kubecolor | |
| chmod +x kubecolor && mv kubecolor /usr/local/bin/ | |
| echo 'alias kubectl="kubecolor"' > /etc/profile.d/kubecolor.sh | |
| source /etc/profile.d/kubecolor.sh | |
| K9SVER=0.51.0 | |
| curl -OL https://github.com/derailed/k9s/releases/download/v${K9SVER}/k9s_$(uname -s)_${ARCH}.tar.gz | |
| tar xfz k9s_$(uname -s)_${ARCH}.tar.gz | |
| rm -rf LICENSE README.md k9s_$(uname -s)_${ARCH}.tar.gz /usr/local/bin/k9s | |
| chmod +x k9s && mv ./k9s /usr/local/bin/k9s | |
| k9s completion bash >/etc/bash_completion.d/k9s | |
| k9s version | |
| mkdir -p ~/.k9s | |
| curl -sSL https://raw.githubusercontent.com/derailed/k9s/master/skins/solarized_dark.yml > ~/.k9s/skin.yml | |
| source /etc/bash_completion.d/k9s | |
| REGCLIENTVER=0.11.5 | |
| curl -OL https://github.com/regclient/regclient/releases/download/v${REGCLIENTVER}/regctl-linux-${ARCH} | |
| mv regctl-linux-${ARCH} /usr/local/bin/regctl | |
| chmod +x /usr/local/bin/regctl | |
| regctl completion bash > /etc/bash_completion.d/regctl | |
| echo | |
| echo | |
| echo "Setup was completed." | |
| kubectl cluster-info | |
| kubectl config get-contexts | |
| kubectl get node -o wide | |
| kubectl get pod -A | |
| kubectl get svc -A | |
| kubectl get csidrivers,sc,volumesnapshotclass,secrets -n default | |
| bold_msg "Kubernetes dashboard (Radar)" | |
| echo "http://radar.${DNSDOMAINNAME}" | |
| echo | |
| bold_msg "Local registry frontend" | |
| echo "http://registry.${DNSDOMAINNAME}:30000" | |
| echo | |
| if [[ "$PHYSICAL" -eq 1 ]]; then | |
| bold_msg "Longhorn Dashboard" | |
| echo "http://$(kubectl -n longhorn-system get ingress longhorn-ingress -o jsonpath='{.spec.rules[0].host}')" | |
| fi | |
| echo | |
| bold_msg "Traefik Dashboard" | |
| echo "http://treafik.${DNSDOMAINNAME}:8080/dashboard/" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment