在网络接口连接到正在运行的虚拟机(或其他资源)之前,Azure 不会分配动态 IP 地址,参考this https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/network_interface#private_ip_address_allocation。所以我认为我们不能在虚拟机创建之前将动态IP转换为静态IP,因为该IP地址暂时不存在。
相反,我们可以通过分配该子网范围内的某些 IP 地址来直接将某些静态 IP 地址关联到 Azure VM。读私有IP https://learn.microsoft.com/en-us/azure/virtual-network/private-ip-addresses#allocation-method分配方法。
Azure 保留每个子网地址范围中的前四个地址。
无法将地址分配给资源。例如,如果
子网的地址范围是 10.0.0.0/16,地址 10.0.0.0-10.0.0.3 和
10.0.255.255 不可用。
例如,您可以参考此模板为虚拟机配置静态私有 IP:
variable "vmlist" {
type = map(object({
hostname = string
IP_address = string
}))
default = {
vm1 ={
hostname = "vma"
IP_address = "10.0.2.4"
},
vm2 = {
hostname = "vmb"
IP_address = "10.0.2.5"
}
}
}
#...
resource "azurerm_network_interface" "staticnic" {
for_each = var.vmlist
name = "${each.value.hostname}-nic"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
ip_configuration {
name = "testconfiguration1"
subnet_id = azurerm_subnet.internal.id
private_ip_address_allocation = "Static"
private_ip_address = each.value.IP_address
}
}
#...
resource "azurerm_virtual_machine" "main" {
for_each = var.vmlist
name = each.value.hostname
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
network_interface_ids = [azurerm_network_interface.staticnic[each.key].id]
vm_size = "Standard_DS1_v2"
# Uncomment this line to delete the OS disk automatically when deleting the VM
# delete_os_disk_on_termination = true
# Uncomment this line to delete the data disks automatically when deleting the VM
# delete_data_disks_on_termination = true
storage_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2016-Datacenter"
version = "latest"
}
storage_os_disk {
name = "${each.value.hostname}-osdisk"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}
os_profile {
computer_name = each.value.hostname
admin_username = "testadmin"
admin_password = "Password1234!"
}
os_profile_windows_config {
provision_vm_agent = "true"
}
}
我在用
Terraform v0.14.7
+ provider registry.terraform.io/hashicorp/azurerm v2.52.0
Update
如果你想让Azure分配动态IP然后将其转换为静态IP,你可以使用本地执行供应者 https://www.terraform.io/docs/language/resources/provisioners/local-exec.html创建资源后调用本地可执行文件。
resource "null_resource" "example" {
for_each = var.vmlist
provisioner "local-exec" {
command = <<EOT
$Nic = Get-AzNetworkInterface -ResourceGroupName ${azurerm_resource_group.main.name} -Name ${azurerm_network_interface.nic[each.key].name}
$Nic.IpConfigurations[0].PrivateIpAllocationMethod = "Static"
Set-AzNetworkInterface -NetworkInterface $Nic
EOT
interpreter = ["PowerShell", "-Command"]
}
}