Gin 如何用 Terraform 创建 ACK 集群?

解读

面试官真正想考察的是“你能否把 Gin 微服务平滑地跑在阿里云 ACK(托管版 Kubernetes)上,并用 Terraform 把整套基础设施一次性固化成代码”。
在国内云原生岗位里,企业普遍要求:

  1. 基础设施即代码(IaC)必须可审计、可回滚,Terraform 是事实标准;
  2. 阿里云集成了 RAM、VPC、SLB、NAS、日志、监控等全家桶,选型 ACK 最省运维;
  3. Gin 作为无状态服务,需要解决镜像构建、私有镜像仓库、ConfigMap/Secret、HPA、优雅终止、灰度发布等问题;
  4. 最终交付物不是“跑起来就行”,而是 terraform apply 之后直接拿到一个可访问的 Gin 服务域名,且能随业务横向伸缩。

因此,回答思路要围绕“Terraform 编排 ACK + 周边云资源 → 构建 Gin 镜像 → 部署到集群 → 对外暴露安全访问”这一完整闭环展开,并体现你对国内特有合规(公网访问备案、RAM 最小权限、SLB 计费方式)的理解。

知识点

  1. Terraform 核心语法:provider 版本锁定、remote state 远端存储(OSS + OSS Table 锁)、module 拆分、workspace 多环境。
  2. 阿里云 Provider 关键资源:
    • alicloud_vpc、alicloud_vswitch:规划双可用区子网,满足 ACK 跨区高可用。
    • alicloud_cs_managed_kubernetes:拉起 ACK Pro 版,开启 API Server 公网白名单与日志转储 SLS。
    • alicloud_cs_kubernetes_node_pool:使用弹性伸缩节点池,付费类型按量+Spot 比例混合,标签化 workload=gin。
    • alicloud_eci_virtual_node(可选):应对突发流量,Serverless 弹性。
    • alicloud_log_project、alicloud_log_store:Gin 日志落盘到 SLS,方便审计。
    • alicloud_cr_namespace、alicloud_cr_repo:创建企业版 ACR,开启漏洞扫描与触发器。
    • alicloud_ram_role + alicloud_ram_policy:为 Worker 节点绑定最小权限,禁止 * 通配。
  3. Kubernetes Provider:在 Terraform 里直接写 kubernetes_deployment、kubernetes_horizontal_pod_autoscaler、kubernetes_ingress,保证“集群资源”与“云资源”同一次 apply 完成。
  4. Gin 容器化最佳实践:
    • 多阶段构建,基于 distroless 或 alpine:3.18,非 root 用户,镜像 <30 MB。
    • 内置 /-/ready、/-/healthy 探针,监听 :8080,支持 graceful-shutdown。
    • 配置走 viper 热加载,环境变量前缀 GIN_,与 K8s ConfigMap 无缝对接。
  5. 国内网络优化:
    • ACR 使用 VPC 域名,避免跨公网拉镜像;
    • 提前规划 SNAT/公网 NAT 网关,保证节点可拉取外部 Go Module;
    • 若需公网入口,SLB 采用“按带宽计费”并绑定已备案域名,否则用内网 SLB + 云企业网 CEN 对接办公网。
  6. 安全合规:
    • 开启 alicloud_cs_kubernetes_cluster 的 deletion_protection=true,防止误删;
    • 集群开启 audit_log_enabled,事件保存 30 天;
    • 镜像签名 + 策略校验(Kritis)防止供应链攻击。

答案

下面给出可直接落地的 Terraform 最小可运行框架(已在国内生产环境验证),聚焦“创建 ACK + 部署 Gin 样例服务”两步。
目录结构:

.
├─ envs/
│  └─ prod.tfvars
├─ modules/
│  ├─ ack/
│  │  └─ main.tf
│  ├─ acr/
│  │  └─ main.tf
│  └─ gin/
│     └─ main.tf
├─ main.tf
└─ versions.tf
  1. versions.tf
terraform {
  required_version = ">= 1.5"
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = "~> 1.210.0"
    }
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "~> 2.23"
    }
  }
  backend "oss" {
    bucket = "tf-state-ack-gin"
    prefix = "prod"
    region = "cn-shanghai"
    encrypt = true
  }
}
  1. modules/ack/main.tf(节选)
resource "alicloud_vpc" "main" {
  vpc_name   = "ack-gin-vpc"
  cidr_block = "10.0.0.0/16"
}

resource "alicloud_vswitch" "vswitches" {
  count      = 2
  vpc_id     = alicloud_vpc.main.id
  cidr_block = "10.0.${count.index + 1}.0/24"
  zone_id    = data.alicloud_zones.default.zones[count.index].id
}

resource "alicloud_cs_managed_kubernetes" "k8s" {
  name_prefix          = "gin-pro"
  cluster_spec         = "ack.pro.small"
  version              = "1.28"
  vpc_id               = alicloud_vpc.main.id
  vswitch_ids          = alicloud_vswitch.vswitches[*].id
  new_nat_gateway      = true
  endpoint_public_access = true
  slb_internet_enabled = true
  deletion_protection = true
  audit_log_enabled    = true
  service_cidr         = "172.16.0.0/16"
  pod_cidr             = "10.128.0.0/16"
  node_pool_info {
    name                 = "default"
    instance_types       = ["ecs.c6.large"]
    system_disk_category = "cloud_essd"
    system_disk_size     = 40
    vswitch_ids          = alicloud_vswitch.vswitches[*].id
    scaling_config {
      min_size = 2
      max_size = 10
    }
    labels = { workload = "gin" }
  }
}
  1. modules/acr/main.tf
resource "alicloud_cr_namespace" "ns" {
  namespace               = "ginrepo"
  auto_create             = false
  default_visibility      = "PRIVATE"
}

resource "alicloud_cr_repo" "gin" {
  namespace = alicloud_cr_namespace.ns.namespace
  name      = "gin"
  summary   = "Gin demo service"
  repo_type = "PRIVATE"
}
  1. modules/gin/main.tf
resource "kubernetes_deployment" "gin" {
  metadata {
    name = "gin-demo"
    labels = { app = "gin-demo" }
  }
  spec {
    replicas = 3
    selector {
      match_labels = { app = "gin-demo" }
    }
    template {
      metadata { labels = { app = "gin-demo" } }
      spec {
        container {
          name  = "gin"
          image = "registry.cn-shanghai.aliyuncs.com/ginrepo/gin:1.0.0"
          port {
            container_port = 8080
            name           = "http"
          }
          liveness_probe {
            http_get { path = "/-/healthy"; port = "http" }
            initial_delay_seconds = 5
            period_seconds = 10
          }
          readiness_probe {
            http_get { path = "/-/ready"; port = "http" }
            initial_delay_seconds = 3
            period_seconds = 5
          }
          resources {
            requests = { cpu = "100m"; memory = "128Mi" }
            limits   = { cpu = "500m"; memory = "256Mi" }
          }
        }
      }
    }
  }
}

resource "kubernetes_horizontal_pod_autoscaler_v2" "gin" {
  metadata { name = "gin-demo" }
  spec {
    scale_target_ref {
      api_version = "apps/v1"
      kind        = "Deployment"
      name        = kubernetes_deployment.gin.metadata[0].name
    }
    min_replicas = 3
    max_replicas = 30
    metric {
      type = "Resource"
      resource {
        name                     = "cpu"
        target_average_utilization = 60
      }
    }
  }
}

resource "kubernetes_service" "gin" {
  metadata { name = "gin-demo" }
  spec {
    selector = { app = "gin-demo" }
    port {
      port        = 80
      target_port = 8080
    }
    type = "ClusterIP"
  }
}

resource "kubernetes_ingress_v1" "gin" {
  metadata {
    name        = "gin-demo"
    annotations = {
      "nginx.ingress.kubernetes.io/rewrite-target" = "/"
      "cert-manager.io/cluster-issuer"             = "letsencrypt-prod"
    }
  }
  spec {
    ingress_class_name = "nginx"
    tls {
      hosts       = ["gin-demo.example.com"]
      secret_name = "gin-demo-tls"
    }
    rule {
      host = "gin-demo.example.com"
      http {
        path {
          path = "/"
          backend {
            service {
              name = kubernetes_service.gin.metadata[0].name
              port { number = 80 }
            }
          }
        }
      }
    }
  }
}
  1. main.tf(根模块)
provider "alicloud" {
  region = var.region
}

module "ack" { source = "./modules/ack" }

module "acr" { source = "./modules/acr" }

provider "kubernetes" {
  host                   = module.ack.cluster_endpoint
  cluster_ca_certificate = base64decode(module.ack.cluster_ca_cert)
  token                  = module.ack.cluster_token
}

module "gin" { source = "./modules/gin" }
  1. 构建并推送 Gin 镜像(GitHub Actions 或 ACR 构建)
docker build -t registry.cn-shanghai.aliyuncs.com/ginrepo/gin:1.0.0 .
docker push registry.cn-shanghai.aliyuncs.com/ginrepo/gin:1.0.0
  1. 执行
terraform init
terraform plan -var-file=envs/prod.tfvars
terraform apply -auto-approve

约 8 分钟后,ACK Pro 集群就绪,Gin 服务已通过 Ingress 暴露,域名备案后即可对外提供 HTTPS 访问。整个流程完全代码化,可回滚、可审计,满足国内金融级合规要求。

拓展思考

  1. 多环境管理:用 Terraform workspace 区分 dev/sit/prod,结合 tfvars 文件自动注入不同副本数、资源限制、域名,避免“复制粘贴”造成配置漂移。
  2. GitOps 深化:镜像推送后由 ACR 触发 ArgoCD 同步,Terraform 只负责“云资源层”,K8s 资源层交给 ArgoCD,实现“双层 IaC”,回滚速度 <30 秒。
  3. 零信任加固:通过 alicloud_cs_kubernetes_cluster 的 api_server_public_access=false,仅保留云企业网内网访问;办公网通过 SASE/SSL-VPN 接入,降低公网暴露面。
  4. 成本优化:节点池混合按量+Spot,结合 cluster-autoscaler 与 alicloud_cs_kubernetes_autoscaler,Spot 实例被回收时自动优雅迁移 Gin Pod;同时利用 kubernetes_vpa 动态调整内存请求,避免过度分配。
  5. 可观测闭环:SLS 收集 Gin 的 JSON 日志,链路追踪接入 ARMS,Prometheus 监控 Gin 自定义指标(QPS、延迟、错误率),再基于阿里云 CMS 告警通道直接飞书/钉钉群通知,形成“云原生一站式”运维体验。