使用Terraform将公共IP地址添加到仅一个Azure虚拟机。

9

我正在通过 azurerm_virtual_machine 中的 count 创建 4 个虚拟机,但我只想创建一个公共 IP 并将其与第一个虚拟机关联,是否可能?如果可以,如何实现?

以下是我的模板文件:

resource "azurerm_network_interface" "nics" {
  count               = 4
  name                = ...
  location            = ...
  resource_group_name = ...
  ip_configuration {
    subnet_id                     = ... 
    private_ip_address_allocation = "Static"
    private_ip_address = ...
  }
}

resource "azurerm_public_ip" "public_ip" {
  name                = ...
  location            = ...
  resource_group_name = ...
}

resource "azurerm_virtual_machine" "vms" {
  count                             = 4
  network_interface_ids             = [element(azurerm_network_interface.nics.*.id, count.index)]
}

我已经阅读了下面的问题,但它们会创建多个公共IP并将它们添加到所有虚拟机中。

使用 Terraform 在 Azure 上创建具有多个公共 IP 的 VM

使用 Terraform 为 Azure 虚拟机设置动态 IP

无法使用 Terraform 创建和附加公共 IP 到 VM

1个回答

11

使用azurerm_public_ip创建公共IP:

resource "azurerm_public_ip" "public_ip" {
  name                = "acceptanceTestPublicIp1"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  allocation_method   = "Dynamic"
}

如果你在azurerm_network_interface中有地址,你可以使用条件表达式来执行以下操作:

resource "azurerm_network_interface" "nics" {
  count               = 4
  name                = ...
  location            = ...
  resource_group_name = ...

  ip_configuration {

    subnet_id                     = ... 
    private_ip_address_allocation = "Static"
    private_ip_address            = ...
    
    public_ip_address_id = count.index == 1 ? azurerm_public_ip.public_ip.id : null
  }
}

1
谢谢,我在问题中放错了前缀,但我需要的是条件检查。谢谢,这很有帮助 :)! - ArigatoManga
@ArigatoManga 没问题。很高兴能帮到你 :-) - Marcin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接