Azure – How to set Static private ip to NIC in Azure using terraform

azureazure-networkingterraform

I am creating a NIC in Azure using terraform script. by default it's allocate dynamic private ip to NIC. If i select private_ip_address_allocation = "Static" then i have to pass Static ip and it's very hard to manage all ips information.

I have tried using like below – Terraform – provision static ip addresses on Azure

resource "azurerm_network_interface" "myterraformnic1" {
  count               = "${var.my_count}"
   name                      = "myNIC1"
    location                  = "eastus"
    resource_group_name       = "${azurerm_resource_group.myterraformgroup.name}"
    network_security_group_id = "${azurerm_network_security_group.myterraformnsg.id}"

    ip_configuration {
        name                          = "myNicConfiguration1"
        subnet_id                     = "${azurerm_subnet.myterraformsubnet.id}"
        private_ip_address_allocation = "static"
        private_ip_address            = "${cidrhost("10.0.1.0/24",  4+count.index)}"

    }

    tags = {
        environment = "Terraform Demo1"
    }
}

It will work for 1 NIC but it i have already 20 NIC assigned with Static ips then not able to get ips and set available static ip.

How can i automate set private ip to Static in terraform code itself ?

Best Answer

There isn't an easy solution to this, unfortunately. If you want a NIC with static internal IP then Azure expects you to tell it what IP you want to use, it will not pick on for you. If you look at the example for doing this with an ARM template, they are cheating and setting the IP to dynamic first, so Azure generates an IP and then changing the mode to static.

So in Terraform, you would need to do something similar, create the NIC with a dynamic IP first, then create the same NIC a second time but make it static this time.

The alternative is to use the cidrsubnet notation in Terraform to generate a valid IP address in your subnet. This will work, but the problem here is you have no guarantee that this IP is not already in use by other resources in your subnet unless you have created them all with Terraform and made sure to increment the IPs each time.

Related Topic