使用 Terraform 创建 EKS 集群,并开启漂移检测定时任务

解读

在国内云原生岗位面试中,这道题表面考“用 Terraform 拉起 EKS”,实则验证候选人三层能力:

  1. 对 IaC 最佳实践的掌握(状态锁、多环境、敏感数据、模块复用);
  2. 对 AWS 中国区(宁夏/北京)与 Global 差异的理解(IAM 认证模式、VPC 结构、Route53 可选性、cn-northwest-1/cn-north-1 分区限制);
  3. 对“漂移检测”这一运维闭环的认知——不是简单打开开关,而是要把“检测→告警→自愈→审计”嵌入 DevOps 流水线,体现 SRE 思维。

面试官常追问:

  • 状态文件放哪?谁对锁负责?
  • 中国区无法直接拉取 docker.io,如何保障节点镜像源?
  • 漂移报警后,是让 Terraform 自动回滚还是只告警?为什么?

知识点

  1. Terraform 核心概念:Provider 版本锁定、State Backend(S3+OSS 对比)、Workspace 隔离、Lifecycle 钩子。
  2. AWS 中国区专属限制:没有 AWS Control Tower、EKS 仅支持 1.21+、IAM OpenID Connect 需要手动创建、STS Endpoint 必须 regional、部分 EC2 实例规格缺失。
  3. EKS 必备组件:eks_cluster、eks_node_group、aws_eks_addon(vpc-cni/kube-proxy/coredns)、aws_auth ConfigMap 的替代品(eks-pod-identity-agent 或 IRSA)。
  4. 漂移检测(Configuration Drift Detection):
    • Terraform 端:terraform plan -detailed-exitcode + 定时 CI;
    • AWS 端:Config Rule、CloudWatch Alarm、SNS 主题;
    • 两者结合:Terraform 输出资源 ARN → Config 自定义规则 → Lambda 回调 Terraform Cloud/Enterprise API 触发 Run。
  5. 高并发 Node.js 场景下的补充:利用 Cluster 模块或 PM2 把 Terraform plan 结果通过 IPC 推送到业务系统,实现“漂移事件”驱动自动伸缩。

答案

下面给出可直接落地中国区的最小可运行模板,并演示如何把“漂移检测”做成 nightly CronJob。生产环境请再叠加 Remote State、OIDC、镜像加速、安全组最小权限等加固。

  1. 目录结构
.
├── main.tf
├── variables.tf
├── versions.tf
├── terraform.tfvars
└── modules/
    ├── eks/
    │   ├── main.tf
    │   ├── variables.tf
    │   └── outputs.tf
    └── drift/
        ├── main.tf
        ├── variables.tf
        └── templates/drift-job.yaml.tpl
  1. versions.tf(锁定中国区可用版本)
terraform {
  required_version = ">= 1.5"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "~> 2.23"
    }
  }
}
provider "aws" {
  region = var.region
  # 中国区需要显式指定 STS endpoint
  endpoints {
    sts = "https://sts.${var.region}.amazonaws.com.cn"
  }
}
  1. modules/eks/main.tf(仅保留核心片段)
resource "aws_eks_cluster" "this" {
  name     = var.name
  role_arn = aws_iam_role.cluster.arn
  version  = var.k8s_version

  vpc_config {
    subnet_ids              = var.subnet_ids
    endpoint_private_access = true
    endpoint_public_access  = false
  }

  # 中国区必须显式依赖 IAM OIDC Provider
  depends_on = [aws_iam_openid_connect_provider.oidc]
}

resource "aws_eks_node_group" "this" {
  cluster_name    = aws_eks_cluster.this.name
  node_group_name = "main"
  node_role_arn   = aws_iam_role.node.arn
  subnet_ids      = var.subnet_ids
  ami_type        = "AL2_x86_64"
  capacity_type   = "ON_DEMAND"
  instance_types  = ["m5.large"]

  scaling_config {
    desired_size = 2
    max_size     = 5
    min_size     = 1
  }

  # 解决中国区镜像拉取慢:写入 bootstrap 脚本
  user_data = base64encode(templatefile("${path.module}/bootstrap.sh", {
    registry_mirror = "registry.cn-hangzhou.aliyuncs.com/google_containers"
  }))
}
  1. 开启漂移检测的两种方案 方案 A:纯 Terraform CI
# modules/drift/main.tf
resource "aws_cloudwatch_event_rule" "nightly" {
  name                = "eks-drift-detection"
  description         = "Trigger drift detection everyday 03:00 Beijing"
  schedule_expression = "cron(0 19 * * ? *)" # 北京时间 03:00
}

resource "aws_cloudwatch_event_target" "sns" {
  rule      = aws_cloudwatch_event_rule.nightly.name
  target_id = "SendToSNS"
  arn       = aws_sns_topic.drift.arn
}

resource "aws_sns_topic" "drift" {
  name = "eks-drift-alerts"
}

resource "aws_sns_topic_subscription" "lambda" {
  topic_arn = aws_sns_topic.drift.arn
  protocol  = "lambda"
  endpoint  = aws_lambda_function.drift.arn
}

resource "aws_lambda_function" "drift" {
  filename         = data.archive_file.drift.output_path
  function_name    = "terraform-plan-check"
  role            = aws_iam_role.lambda.arn
  handler         = "index.handler"
  runtime         = "nodejs18.x"
  timeout         = 900
  environment {
    variables = {
      TF_CLOUD_TOKEN = var.tf_cloud_token
      WORKSPACE_NAME = "prod-eks"
    }
  }
}

data "archive_file" "drift" {
  type        = "zip"
  output_path = "${path.module}/drift.zip"
  source {
    content  = file("${path.module}/drift.js")
    filename = "index.js"
  }
}

drift.js 核心逻辑(Node.js 18)

const https = require('https');
exports.handler = async () => {
  const options = {
    hostname: 'app.terraform.io',
    path: `/api/v2/workspaces/${process.env.WORKSPACE_NAME}/runs`,
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.TF_CLOUD_TOKEN}`,
      'Content-Type': 'application/vnd.api+json'
    }
  };
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      if (res.statusCode === 201) {
        resolve({ statusCode: 200, body: 'Drift detection run triggered' });
      } else {
        reject(new Error(`TF API ${res.statusCode}`));
      }
    });
    req.write(JSON.stringify({
      data: {
        type: 'runs',
        attributes: { message: 'Nightly drift check', auto-apply: false }
      }
    }));
    req.end();
  });
};

方案 B:K8s CronJob(适合已跑在 EKS 里的 Terraform 镜像)

resource "kubernetes_cron_job_v1" "drift" {
  metadata {
    name      = "terraform-drift"
    namespace = "kube-system"
  }
  spec {
    schedule = "0 3 * * *" # 北京时间 11:00,镜像内 TZ=Asia/Shanghai
    job_template {
      spec {
        template {
          spec {
            restart_policy = "OnFailure"
            container {
              name  = "terraform"
              image = "registry.cn-hangzhou.aliyuncs.com/acs/terraform:1.5"
              command = ["sh", "-c", <<-EOF
                terraform init -backend-config="bucket=your-oss-bucket" -backend-config="region=cn-hangzhou"
                terraform plan -detailed-exitcode
                if [ $? -eq 2 ]; then
                  echo "Drift detected" | curl -X POST -d @- https://your-webhook/alert
                fi
              EOF
              ]
              env {
                name  = "ALICLOUD_ACCESS_KEY"
                value_from { secret_key_ref { name = "alicloud-creds", key = "access-key" } }
              }
              env {
                name  = "ALICLOUD_SECRET_KEY"
                value_from { secret_key_ref { name = "alicloud-creds", key = "secret-key" } }
              }
            }
          }
        }
      }
    }
  }
}
  1. 一键应用
export AWS_REGION=cn-northwest-1
terraform init
terraform plan -out=tfplan
terraform apply tfplan
  1. 验证漂移 手动改动控制台:把 EKS 节点组 desired 改为 3。次日 03:00,Lambda 会触发 Terraform Cloud Run,计划报告显示“漂移”,钉钉/飞书收到卡片消息,人工确认后可回滚。

拓展思考

  1. 如果公司把状态锁在阿里云 OSS,Terraform Enterprise 又放在海外,跨境延迟导致 plan 超时,如何优化?(提示:使用 OSS 跨区域复制 + 本地只读缓存,或在 CI 内网搭建 Terraform Runner)
  2. 中国区没有 AWS Config,如何用阿里云 Config 规则替代,实现跨云漂移统一治理?
  3. 当 Node.js 微服务通过 IRSA 调用 S3 时,如果手动改了 IAM Policy,Terraform 状态未感知,导致“静默漂移”。怎样在应用层埋点,把运行时权限收敛回 Terraform 模板?(思路:每次服务启动把当前 Policy Version 推送到 OTS,定时对比)
  4. 把“漂移检测”结果作为 HPA 的自定义指标,实现“配置漂移→业务副本数惩罚”的闭环,是否可行?会带来哪些风险?