azureterraformazure-virtual-machineterraform-provider-azureazure-public-ip

terraform: add public IP to only one azure VM


I'm creating 4 vms through count in azurerm_virtual_machine but i want to create only one public IP and associate it with the first VM ? is that possible if so how ?

below is my template file

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)]
}

i have already gone through below questions but they are create multiple public ip's & add them to all vms.

multiple-vms-with-public-ip

set-dynamic-ip

attach-public-ip


Solution

  • Public IPs are created using azurerm_public_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"
    }
    

    Having the address in your azurerm_network_interface you could do the following using Conditional Expressions:

    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
      }
    }