从零到成熟模块详解

基础设施即代码 · 第 11 / 13 章

11综合实操:一键创建网络 + 集群 + 节点池并完整销毁

这一章是一次完整的闭环演练,目标是检验前 10 章的能力是否真的连起来了:用一份变量文件,在一个空的云账号里创建 VPC + EKS 集群 + 托管节点池,验证服务能跑起来,然后完整销毁并让次日账单归零。全程大约 2 小时,其中 apply 与 destroy 各占 20 分钟左右,其余时间用来验证与清理。

11.1 目标、资源清单与成本

先算清楚这次实验要花多少钱,再决定做不做。下面是 ap-southeast-1 区域的按需价格(2024 年 5 月口径),实验环境全部用最小规格:

资源规格单价每小时
EKS 控制面标准支持0.10 美元/小时0.100
托管节点组2 × c7g.large(2 核 4G)0.0725 美元/小时/台0.145
NAT 网关单个(非高可用)0.045 美元/小时0.045
其它EBS 20GB × 2、EIP、流量—约 0.030
合计——约 0.32 美元/小时 = 7.7 美元/天

结论:半天内做完并销毁,成本约 2 美元;放一个周末不管就是 23 美元;放一个月是 231 美元。所以这次实操的最后一项验收不是「集群能跑」,而是销毁之后账单归零。

11.2 代码骨架:三层、三个 state、三种生命周期

按第 3.4 节的边界,分为 network、cluster、nodepool 三层。实验环境为了省事可以放在一个目录里,但必须用同一个 backend 加不同的 key 前缀,否则你学不到「state 边界」这件事。为了聚焦,模块直接引用社区模块并锁版本:

terraform {
        required_version = ">= 1.7.0"
        backend "s3" {
          bucket         = "acme-tfstate-lab"
          key            = "lab/network/terraform.tfstate"
          region         = "ap-southeast-1"
          dynamodb_table = "acme-tfstate-lock"
          encrypt        = true
        }
      }

      locals {
        common_tags = {
          managed-by = "terraform"
          env        = "lab"
          owner      = "team-platform"
          expire-at  = "2024-05-31"
        }
      }

      module "vpc" {
        source  = "terraform-aws-modules/vpc/aws"
        version = "5.8.1"

        name = "lab-vpc"
        cidr = "10.42.0.0/16"

        azs             = ["ap-southeast-1a", "ap-southeast-1b", "ap-southeast-1c"]
        private_subnets = ["10.42.1.0/24", "10.42.2.0/24", "10.42.3.0/24"]
        public_subnets  = ["10.42.101.0/24", "10.42.102.0/24", "10.42.103.0/24"]

        enable_nat_gateway   = true
        single_nat_gateway   = true      # 实验环境用 1 个 NAT,省 0.045 美元/小时
        enable_dns_hostnames = true

        tags = local.common_tags
      }

      output "vpc_id" {
        value = module.vpc.vpc_id
      }

      output "private_subnet_ids" {
        value = module.vpc.private_subnets
      }

集群层与节点池层各自一个目录,通过 data 读取对方的输出(实验环境用 terraform_remote_state 最省事,生产环境请改用 SSM 参数,理由见第 3.4 节):

data "terraform_remote_state" "network" {
        backend = "s3"
        config = {
          bucket = "acme-tfstate-lab"
          key    = "lab/network/terraform.tfstate"
          region = "ap-southeast-1"
        }
      }

      # 本层的 locals 与网络层保持一致,标签规范见第 9 章
      locals {
        common_tags = {
          managed-by = "terraform"
          env        = "lab"
          owner      = "team-platform"
          expire-at  = "2024-05-31"
        }
      }

      module "eks" {
        source  = "terraform-aws-modules/eks/aws"
        version = "20.13.1"

        cluster_name    = "lab"
        cluster_version = "1.29"

        vpc_id     = data.terraform_remote_state.network.outputs.vpc_id
        subnet_ids = data.terraform_remote_state.network.outputs.private_subnet_ids

        cluster_endpoint_public_access = true    # 只为实验方便;生产应限制 CIDR

        eks_managed_node_groups = {
          general = {
            instance_types = ["c7g.large"]
            min_size       = 2
            max_size       = 4
            desired_size   = 2

            labels = {
              role = "general"
              env  = "lab"
            }

            # 只有需要专用硬件的负载才用 taint;实验里先不加,避免调度不上
            tags = local.common_tags
          }
        }

        tags = local.common_tags

        # 注意:节点组会依赖 addon 与 aws-auth 配置;如果它们放在同一个 module 里,
        # 用 node_groups_depends_on 显式声明依赖,避免节点先于授权就绪而 NotReady
      }

变量与标签的收尾工作照第 9 章做:owner、env、expire-at 全部由 locals 注入,managed-by = terraform 用于第 5 章的漂移检测。

11.3 创建与验证:验收判据写死在命令里

创建顺序必须是 network → cluster → nodepool,因为后者的输入来自前者。apply 的时间预期:网络层约 2 分钟(NAT 网关创建最慢),集群控制面约 11 分钟,节点组约 3 分钟,合计 16–20 分钟。验证阶段用四条命令,覆盖网络、控制面、调度与真实负载四个层面(完整命令见本章 lab)。

这里有三个容易被跳过的验收点:(1) 节点必须能解析集群内的域名(CoreDNS 正常),用 kubectl run --rm -it dnstest --image=busybox:1.36 -- nslookup kubernetes.default 验证;(2) 节点必须能出网(NAT 生效),否则镜像拉取会以 ImagePullBackOff 的形式失败——这是新手最常卡住的地方;(3) 集群里的节点必须带上第 9 章的标签,否则成本归属到不了团队。

11.4 销毁与残留清理:真正的验收

terraform destroy 成功返回不代表资源清理干净。EKS 场景有四类典型残留:

  1. ENI 与安全组:Kubernetes 的 Service(type=LoadBalancer)创建过 LB,删除时如果 LB 还在,会留下 ENI 挂在子网里,导致 terraform destroy 删除安全组时报 DependencyViolation。
  2. EBS 卷:PVC 动态创建的卷默认回收策略是 Delete,但如果是通过 StorageClass 之外的路径创建的(比如手工 kubectl apply 的 PV),销毁集群不会删卷。一个 20GB gp3 卷月成本约 1.6 美元,看着不多,但这类残留通常会积累。
  3. CloudWatch 日志组:EKS 控制面日志组 /aws/eks/lab/cluster 不归 Terraform 管(除非显式创建),默认保留「永不过期」,会持续产生存储费用。
  4. KMS 密钥:EKS 的 secrets 加密密钥(如果启用了)有 7 天的待删除窗口,期间状态是 PendingDeletion,不产生显著费用但不能立即释放,属正常现象。

清理顺序是:先删集群内的负载(LB / PVC)→ terraform destroy 节点池 → 控制面 → 网络 → 最后跑残留巡检。如果先 destroy 集群再删 LoadBalancer Service,LB 的 ENI 会失去控制器管理,只能手工删。

真实场景 · destroy 卡在 DependencyViolation,外加一个月的残留卷

这是我们在第一次演练里真实遇到的输出:

module.eks.module.node_groups.aws_eks_node_group.this["general"]: Destruction complete
      module.vpc.aws_security_group.default: Still destroying... [id=sg-0a1b2c3d4e5f60718, 4m10s elapsed]
      ╷
      │ Error: deleting EC2 Security Group (sg-0a1b2c3d4e5f60718): DependencyViolation:
      │   resource sg-0a1b2c3d4e5f60718 has a dependent object
      ╵

排查路径(按顺序执行,总耗时约 40 分钟):

  • aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-0a1b2c3d4e5f60718 --query "NetworkInterfaces[].[NetworkInterfaceId,Description,Status]" --output table,输出显示一个 available 状态的 ENI,Description 是 ELB net/lab-k8s-.../...。
  • 顺着名字查 LB:aws elbv2 describe-load-balancers --query "LoadBalancers[?contains(LoadBalancerName,'lab')]" --output table,发现集群里那个测试用的 nginx Service 创建的 LB 还在——它在节点组被销毁之后失去了控制器,永不被回收。
  • 删除 LB 与它的 target group 后,ENI 在 90 秒内自动释放,再跑一次 terraform destroy 成功。

更贵的残留发生在两周之后:财务提醒账号里有一条 1.6 美元/月的 EBS 费用。查出来是演练时的一个 PVC 留下的 20GB gp3 卷,因为当时它是用 kubectl apply 手工创建的 PV(没有走 StorageClass),回收策略是 Retain。它在那里躺了 34 天,虽然只花了 1.8 美元,但如果不是财务提醒,谁也不会发现——这正是第 9 章所说的「归属缺失的隐藏顺序」。

固化下来的两条规矩:(1) 演练的销毁顺序里,删集群内负载永远是第一步,且必须用 kubectl get svc --all-namespaces 确认没有 type=LoadBalancer 的 Service 残留;(2) 销毁之后 24 小时内必须跑一次残留巡检(本章 lab 的最后一段),巡检结果附在演练记录里。

动手 · 完整的 apply → 验证 → destroy → 归零闭环(前置:Terraform 1.7+、awscli、kubectl、一个有 5 美元额度的账号)
  1. 准备 backend 与代码:
    BUCKET=acme-tfstate-lab; REGION=ap-southeast-1
          aws s3api create-bucket --bucket "$BUCKET" --region "$REGION" \
            --create-bucket-configuration LocationConstraint="$REGION"
          aws s3api put-bucket-versioning --bucket "$BUCKET" --versioning-configuration Status=Enabled
          aws s3api put-bucket-encryption --bucket "$BUCKET" \
            --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
          aws dynamodb create-table --table-name acme-tfstate-lock \
            --attribute-definitions AttributeName=LockID,AttributeType=S \
            --key-schema AttributeName=LockID,KeyType=HASH \
            --billing-mode PAY_PER_REQUEST --region "$REGION" \
            --query 'TableDescription.TableStatus' --output text
    预期最后一行输出 CREATING(约 20 秒后变成 ACTIVE)。
  2. 创建网络层:
    cd envs/lab/network
          terraform init -no-color | tail -2
          terraform fmt -check -recursive && terraform validate
          terraform plan -out=tfplan -no-color | tail -5
          time terraform apply -no-color tfplan | tail -3
    预期 plan 输出 Plan: 24 to add, 0 to change, 0 to destroy.(VPC + 3 私有子网 + 3 公有子网 + IGW + 1 NAT + 路由表 + EIP 等),apply 用时约 2 分钟。
  3. 创建集群与节点池:
    cd ../cluster && terraform init -no-color >/dev/null && time terraform apply -auto-approve -no-color | tail -3
          # 预期:Apply complete! Resources: 41 added ...  耗时约 11 分钟
          # 涉及账单,这里用 -auto-approve 只是为了实验;生产环境按第 4 章的流程走人工审批
  4. 验证(四项判据,缺一不可):
    aws eks update-kubeconfig --name lab --region ap-southeast-1
          kubectl get nodes -o wide
          # 预期:2 个节点,STATUS=Ready,INTERNAL-IP 落在 10.42.1-3.0/24 内
          kubectl run --rm -it dnstest --image=busybox:1.36 --restart=Never -- nslookup kubernetes.default
          # 预期:Name: kubernetes.default  Address: 172.20.0.1
          kubectl run nginx --image=nginx:1.25.4 --port=80
          kubectl wait --for=condition=Ready pod/nginx --timeout=120s
          kubectl get pod nginx -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,IP:.status.podIP
          # 预期:nginx 调度到某个节点上且 STATUS 不是 Pending / ImagePullBackOff
    如果卡在 ImagePullBackOff,先查节点的出网能力:kubectl run nettest --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T5 https://registry-1.docker.io/v2/,超时说明 NAT 或路由有问题(第 11.3 节的第二个验收点)。
  5. 销毁:顺序很重要:
    kubectl delete pod nginx --force --grace-period=0
          kubectl get svc --all-namespaces | grep LoadBalancer || echo "OK:没有 LoadBalancer 类型的 Service"
          cd ../cluster && time terraform destroy -auto-approve -no-color | tail -3   # 约 9 分钟
          cd ../network && time terraform destroy -auto-approve -no-color | tail -3   # 约 4 分钟
  6. 残留巡检(本章最重要的验收):
    REGION=ap-southeast-1
          echo "--- 未挂载的卷"; aws ec2 describe-volumes --region $REGION \
            --filters Name=status,Values=available \
            --query "Volumes[].[VolumeId,Size,CreateTime]" --output text
          echo "--- 名字含 lab 的 LB"; aws elbv2 describe-load-balancers --region $REGION \
            --query "LoadBalancers[?contains(LoadBalancerName,'lab')].LoadBalancerName" --output text
          echo "--- EKS 日志组"; aws logs describe-log-groups --region $REGION \
            --log-group-name-prefix /aws/eks/lab --query "logGroups[].logGroupName" --output text
          echo "--- 名字含 lab 的安全组"; aws ec2 describe-security-groups --region $REGION \
            --filters Name=tag:env,Values=lab --query "SecurityGroups[].[GroupId,GroupName]" --output text
    预期除日志组外全部为空。日志组的处理:aws logs delete-log-group --log-group-name /aws/eks/lab/cluster --region ap-southeast-1。第二天再核一次账单——Cost Explorer 里该账号当日成本应为 0 美元(不含已产生的按量计费),这是本次实操的最终判据。
忘记销毁的代价是线性的,而且不会自己停下来

这次实验环境的成本是 0.32 美元/小时。忘记 3 天是 23 美元,忘记 30 天是 231 美元,如果按「反正是实验」把节点池调到 6 台 c7g.xlarge,一个月就是 2,100 美元。更麻烦的是它不会触发任何告警:实验环境没有 SLO、没有业务指标,只有一条越来越大的账单。

三个必做的护栏:(1) 所有实验资源必须带 expire-at 标签(第 9 章),并由一个每天运行的任务检查过期资源;(2) 给实验用账号设预算告警(AWS Budgets:超过 20 美元发邮件给 owner);(3) 养成「先写销毁脚本,再写创建脚本」的习惯——如果 terraform destroy 跑不通,说明创建时的依赖设计有问题,这正是第 11.4 节要你踩的坑。

基础设施即代码 · 第 11 章 综合实操:一键创建网络 + 集群 + 节点池并完整销毁
模块目录 · 返回学习路径