workers.tf 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # 循环清理所有 worker 节点
  2. resource "null_resource" "k3s_cleanup_worker" {
  3. count = length(var.worker_ips)
  4. connection {
  5. type = "ssh"
  6. host = var.worker_ips[count.index]
  7. user = "root"
  8. password = var.worker_password
  9. }
  10. provisioner "remote-exec" {
  11. inline = [
  12. "# Stop k3s-agent service if running",
  13. "systemctl stop k3s-agent 2>/dev/null || true",
  14. "# Kill any remaining k3s processes",
  15. "pkill -f k3s 2>/dev/null || true",
  16. "# Remove k3s data directory",
  17. "rm -rf /var/lib/rancher/k3s",
  18. "# Remove k3s-agent service file",
  19. "rm -f /etc/systemd/system/k3s-agent.service",
  20. "systemctl daemon-reload 2>/dev/null || true",
  21. "echo 'Cleanup completed on worker node ${count.index + 1}'"
  22. ]
  23. }
  24. }
  25. # 循环安装所有 worker 节点(修复了多行字符串问题)
  26. resource "null_resource" "k3s_install_worker" {
  27. count = length(var.worker_ips)
  28. depends_on = [null_resource.copy_token_to_workers, null_resource.k3s_cleanup_worker]
  29. connection {
  30. type = "ssh"
  31. host = var.worker_ips[count.index]
  32. user = "root"
  33. password = var.worker_password
  34. }
  35. provisioner "remote-exec" {
  36. inline = [
  37. "if [ -f /usr/local/bin/k3s ]; then",
  38. " echo 'k3s binary already exists, skipping download'",
  39. "else",
  40. " wget -O /usr/local/bin/k3s ${var.k3s_download_url}",
  41. " chmod +x /usr/local/bin/k3s",
  42. "fi",
  43. "TOKEN=$(cat /root/node-token)",
  44. "echo -e '\\033[32m--Install k3s-agent systemd service--\\033[0m'",
  45. # 关键修复:使用 heredoc 写入多行 systemd 配置
  46. <<EOT
  47. cat > /etc/systemd/system/k3s-agent.service <<'EOF'
  48. [Unit]
  49. Description=Lightweight Kubernetes
  50. Documentation=https://k3s.io
  51. After=network-online.target
  52. Wants=network-online.target
  53. [Service]
  54. Type=notify
  55. ExecStart=/usr/local/bin/k3s agent --server https://${var.master_ip}:6443 --token $TOKEN --node-name worker-node-${replace(var.worker_ips[count.index], ".", "-")} --node-external-ip=${var.worker_ips[count.index]} --data-dir /var/lib/rancher/k3s
  56. KillMode=process
  57. Delegate=yes
  58. LimitNOFILE=1048576
  59. LimitNPROC=infinity
  60. LimitCORE=infinity
  61. TasksMax=infinity
  62. TimeoutStartSec=0
  63. Restart=always
  64. RestartSec=5s
  65. [Install]
  66. WantedBy=multi-user.target
  67. EOF
  68. EOT
  69. ,
  70. "systemctl daemon-reload",
  71. "systemctl enable --now k3s-agent",
  72. "echo -e '\\033[32m--k3s agent started successfully--\\033[0m'",
  73. "sleep 3",
  74. ]
  75. }
  76. }