Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...