Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65935259/terraform-add-public-ip-to-only-one-azure-vm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...