You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Terraform传入变量动态生成ENIConfig YAML并执行kubectl apply

实现方案

1. 定义Terraform变量

首先在variables.tf中声明入参,建议将AZ名称、子网ID绑定为结构化变量,避免两个独立列表索引错位的问题:

variable "eni_configs" {
  type = list(object({
    az_name   = string
    subnet_id = string
  }))
  description = "ENI配置列表,包含对应AZ名称和子网ID"
}

variable "eks_security_group_id" {
  type = string
  description = "EKS集群使用的安全组ID"
}

在.tfvars中传入对应值即可:

eks_security_group_id = "sg-xxxxxx"
eni_configs = [
  {
    az_name   = "az1"
    subnet_id = "subnet_id1"
  },
  {
    az_name   = "az2"
    subnet_id = "subnet_id2"
  },
  {
    az_name   = "az3"
    subnet_id = "subnet_id3"
  }
]

2. 编写YAML模板文件

新建eni_config.tpl模板文件,单个模板对应单份ENIConfig配置,无需在模板内写循环:

apiVersion: crd.k8s.amazonaws.com/v1alpha1
kind: ENIConfig
metadata: 
  name: ${az_name}
spec: 
  securityGroups: 
    - ${sg_id}
  subnet: ${subnet_id}

3. 动态生成多份独立YAML文件

用local_file资源配合for_each遍历变量,生成按AZ命名的独立YAML文件,不需要嵌套循环:

resource "local_file" "eni_config" {
  for_each = { for idx, cfg in var.eni_configs : idx => cfg }
  filename = "${path.module}/eni-config-${each.value.az_name}.yaml"
  content = templatefile("${path.module}/eni_config.tpl", {
    az_name   = each.value.az_name
    subnet_id = each.value.subnet_id
    sg_id     = var.eks_security_group_id
  })
}

4. 配置null_resource执行kubectl apply

创建null_resource依赖所有生成的YAML文件,配置变更时自动触发生效:

resource "null_resource" "apply_eni_configs" {
  depends_on = [local_file.eni_config]

  provisioner "local-exec" {
    command = <<EOT
kubectl apply -f ${path.module}/ --include='eni-config-*.yaml'
EOT
  }

  triggers = {
    eni_configs_hash = sha1(jsonencode(var.eni_configs))
    sg_id_hash       = sha1(var.eks_security_group_id)
  }
}

如果需要删除资源时同步清理K8s配置,可以补充when = destroy的local-exec provisioner执行delete命令。

注意事项
  • 执行Terraform的环境需要提前配置好kubectl权限,确保能正常访问目标EKS集群
  • 不建议把多份ENIConfig配置拼接在同一个文件中,拆分的独立文件更便于后续排查和手动调整

内容的提问来源于stack exchange,提问作者Samuel Syed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:06:03