terraform azure public ip 和 public ip 前缀

terraform azure public ip and public ip prefix

我正在尝试创建一个 Azure public IP 前缀 (/30),然后从该前缀分配一个 public IP(4 次),然后将它们分配为输出以在单独的模块稍后。我想在列出的 NIC 中分配一个 IP,然后将其他 3 个“保存”为输出以备后用。但是,我收到以下错误:

│ The "count" object can only be used in "module", "resource", and "data"
│ blocks, and only when the "count" argument is set.

我也在努力解决如何将每个 IP 引用为输出的语法(我在下面包含了 outputs.tf 但知道语法是错误的):

main.tf

resource "azurerm_public_ip_prefix" "ipprefix" {
  name                    = "tempprefixname"
  location                = var.rglocation
  resource_group_name     = var.rgname

  prefix_length = 30
}

resource "azurerm_public_ip" "publicip" {
  count                 = 4
  name                  = "${var.publicipname}-${count.index}"
  location              = var.rglocation
  resource_group_name   = var.rgname
  allocation_method     = "Static"
  sku                   = "Basic"
  public_ip_prefix_id   = azurerm_public_ip_prefix.ipprefix.id
}

resource "azurerm_network_interface" "nic" {
  name                    = var.nicname
  location                = var.rglocation
  resource_group_name     = var.rgname

  ip_configuration {
    name                          = var.ipconfigname
    subnet_id                     = azurerm_subnet.subnet.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.publicip[count.index].id
  }
}

outputs.tf

output "publicipoutput1" {
    value = azurerm_public_ip.publicip.ip_address[count.1]
}
output "publicipoutput2" {
    value = azurerm_public_ip.publicip.ip_address[count.2]
}
output "publicipoutput3" {
    value = azurerm_public_ip.publicip.ip_address[count.3]
}
output "publicipoutput4" {
    value = azurerm_public_ip.publicip.ip_address[count.4]
}

当您开始使用 count 时,您必须在所有引用使用 count [1] 创建的任何其他资源的地方使用它。所以,如果你在 azurerm_public_ip 中使用了 count,你也必须在 azurerm_network_interface 中使用 count 而不仅仅是 count.index:

resource "azurerm_network_interface" "nic" {
  count               = 4
  name                = var.nicname
  location            = var.rglocation
  resource_group_name = var.rgname

  ip_configuration {
    name                          = var.ipconfigname
    subnet_id                     = azurerm_subnet.subnet.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.publicip[count.index].id
  }
}

正如您从错误中看到的那样,output 不能使用 count,但是您可以 select 使用 splat 表达式 [2]:[=23] 的所有值=]

output "public_ip_addresses" {
    value = [ azurerm_public_ip.publicip[*].ip_address ]
}


[1] https://www.terraform.io/language/meta-arguments/count

[2] https://www.terraform.io/language/expressions/splat