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

如何在Terraform libvirt资源中为前两个worker节点条件分配GPU

解决方案

你当前的错误核心是dynamic块的for_each逻辑设置错误,不需要遍历worker集合,只要针对当前实例的索引做条件判断,符合要求时才生成GPU分配的XML块即可。
修改后的完整代码如下:

resource "libvirt_domain" "worker" {
    count   = var.worker["count"]
    name    = "${var.cluster_id}-worker-${count.index}"
    memory  = var.worker.memory
    vcpu    = var.worker.vcpu

    coreos_ignition = libvirt_ignition.worker[count.index].id

    disk {
        volume_id = libvirt_volume.worker[count.index].id
    }
    console {
        type        = "pty"
        target_port = 0
    }
    cpu = {
        mode = var.cpu_mode
    }
    network_interface {
        network_id  = var.network_id
        hostname    = "worker-${count.index}.${var.cluster_id}.${var.cluster_domain}"
        mac         = var.worker_macs[count.index]
    }

    dynamic "xml" {
        # 仅索引为0、1的实例会生成xml块
        for_each = count.index < 2 ? [count.index] : []
        content {
            xslt = file("add_gpu_w${xml.value}.xsl")
        }
    }
}

说明

  1. 三元表达式count.index < 2 ? [count.index] : []会在当前worker索引小于2时返回包含当前索引的单元素列表,触发xml块生成;其余情况返回空列表,不会生成xml块,符合你仅给前两个worker分配GPU的需求
  2. 请确认add_gpu_w0.xsl和add_gpu_w1.xsl文件存放在Terraform工作目录的正确路径下,避免文件读取报错
  3. 如果后续需要调整分配GPU的worker数量,直接修改count.index < 2中的阈值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:57:06