Terraform 模块说明
Terraform 代码分为两层:aliyun/、tencent/ 是 root module,modules/ 下是可复用子模块。root module 负责把变量、标签、模块依赖和输出连接起来;子模块只负责单类资源。
调用关系
Root module
root module 的核心职责:
locals {
node_groups = {
master = {
count = var.master_count
instance_type = var.master_instance_type
}
worker = {
count = var.worker_count
instance_type = var.worker_instance_type
}
}
}
这段 locals 把 master 和 worker 的数量、规格整理成统一结构,传给 ECS/CVM 模块。这样两云节点模块都能用类似输入。
root module 还负责输出后续脚本需要的信息:
output "master_private_ips" {
value = module.ecs.master_private_ips
}
output "k8s_api_lb_public_ip" {
value = module.lb.k8s_api_lb_public_ip
}
这些 output 会被 make aliyun-output 和 make tencent-output 写入 generated/*/terraform-output.json。
VPC 模块
VPC 模块负责网络容器和一个默认子网:
| 云 | 文件 | 资源 |
|---|---|---|
| 阿里云 | modules/aliyun-vpc/main.tf | alicloud_vpc、alicloud_vswitch |
| 腾讯云 | modules/tencent-vpc/main.tf | tencentcloud_vpc、tencentcloud_subnet、tencentcloud_route_table |
它不负责 PodCIDR、ServiceCIDR 和 Cilium 路由,这些属于 Kubernetes 网络层。
安全组模块
安全组模块开放这些端口:
| 端口 | 协议 | 用途 |
|---|---|---|
22 | TCP | SSH |
6443 | TCP | Kubernetes API |
10250 | TCP | kubelet |
4240 | TCP | Cilium health |
4244 | TCP | Hubble 预留 |
32379 | TCP | Cluster Mesh NodePort |
8472 | UDP | Cilium VXLAN |
51820 | UDP | WireGuard |
admin_cidrs 控制 SSH 和管理端 API 访问来源。测试时也不要长期使用 0.0.0.0/0。
ECS/CVM 模块
节点模块负责:
- 读取或创建 SSH key。
- 按
node_groups创建 master 和 worker。 - 绑定安全组和子网。
- 输出公网 IP、私网 IP、实例 ID。
输出被三个地方消费:
scripts/setup-wireguard-underlay.sh读取节点 IP 配置 WireGuard。scripts/render-kubeadm-config.sh读取 master IP 和 API LB 渲染 kubeadm。- LB 模块读取实例 ID 作为后端。
LB 模块
LB 模块创建两个入口:
| 入口 | 前端端口 | 后端 |
|---|---|---|
| Kubernetes API | 6443 | master 节点 6443 |
| Cluster Mesh API | 2379 | 所有节点 32379 |
Cluster Mesh 后端使用所有节点,是因为 clustermesh-apiserver 通过 NodePort 暴露,任一节点都可以接收流量再转发到对应 Pod。
VPN 模块
VPN 模块保留托管 IPsec VPN 路线,但默认关闭:
enable_vpn_gateway = false
enable_vpn_connection = false
如果后续需要切换到云厂商托管 VPN,流程是:
- 两侧先开启
enable_vpn_gateway创建网关。 - 导出一侧 VPN 公网 IP,填入对侧变量。
- 设置相同
vpn_psk。 - 开启
enable_vpn_connection创建连接和路由。
当前阶段默认使用 WireGuard,避免 VPN 成本和厂商连接差异影响 Kubernetes 链路验证。
维护约束
- 新增变量时,两云同类变量尽量同名或语义一致。
- outputs 只暴露脚本需要的信息。
- 不把真实变量、state、kubeconfig、token、证书写进文档。
- 每次修改 Terraform 后运行:
terraform fmt -check -recursive
terraform -chdir=aliyun validate
terraform -chdir=tencent validate