【问题标题】:How to interpolate COUNT in Terraform?如何在 Terraform 中插入 COUNT?
【发布时间】:2019-09-03 10:03:22
【问题描述】:

我正在 Azure 中创建多个具有相应 NIC 和 PublicIP 的 VM。

我可以为虚拟机创建唯一的名称,这没问题:

resource "azurerm_virtual_machine" "workernode" {
    count = "${var.nodeCount}"
    name = "workernode-${count.index +1}"

和公共 IP:

resource "azurerm_public_ip" "AliasworkerPubIP" {
    count = "${var.nodeCount}"
    name = "workerpubip${count.index +1}"

和网卡:

resource "azurerm_network_interface" "workerNIC" {
    count = "${var.nodeCount}"
    name = "workerNIC.${count.index +1}"  

但我不知道如何让它工作,然后将 NIC 连接到刚刚创建的 PublicIP ...

尝试了各种不同的方法,但没有任何效果...我知道我遗漏了一些东西或没有正确理解插值解析,但是什么?!

我试过的例子:

public_ip_address_id = "${azurerm_public_ip}.${format("Alias_WorkerIP%d.id", count.index +1)}" 

public_ip_address_id = "${format("Alias_WorkerIP%d.id", count.index +1)}"

public_ip_address_id = "${format("azurerm_public_ip.workerpubip.%s.id", count.index +1)}" 

对我哪里出错有什么想法吗?

【问题讨论】:

    标签: azure terraform


    【解决方案1】:

    目前推荐的表达方式是:

    public_ip_address_id = "${azurerm_public_ip.workerpubip.*.id[count.index]}"
    

    使用这个索引运算符 ([ ... ]) 可以让 Terraform 更好地理解这意味着的依赖关系,因此如果只需要替换一个公共 IP 实例,它可以理解只有一个对应的 azurerm_network_interface 需要更新了。

    当使用 element 函数时,Terraform 仅“看到”azurerm_public_ip.workerpubip.*.id 表达式,并且保守地假设存在对 所有 azurerm_public_ip id 的依赖。

    【讨论】:

      【解决方案2】:

      我就是这样解决的:

      public_ip_address_id = "${element(azurerm_public_ip.workerpubip.*.id,count.index)}"

      【讨论】:

        【解决方案3】:

        在 azurerm_network_interface 模块中试试这个

         public_ip_address_id          = "${element(azurerm_public_ip.main-rg__vm-ip.*.id, count.index)}"
        
        

        在 azurerm_public_ip 模块中

        resource azurerm_public_ip main-rg__vm-ip {
          count               = "${var.vm_count}"
          name                = "${var.environment}-vm${count.index+1}-ip"
          location            = "${var.location}"
          resource_group_name = "${azurerm_resource_group.main-rg.name}"
          sku                 = "Basic"
          allocation_method   = "Dynamic"
        
        
        }
        

        【讨论】:

          猜你喜欢
          • 2019-09-30
          • 2022-08-19
          • 1970-01-01
          • 2015-10-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-28
          • 2017-10-01
          相关资源
          最近更新 更多