2

I am trying to see if there is a way in Terraform code to optional provide the need for a variable based on the input of a different variable. For example, I have a module that creates a NIC within Azure, the code can look like the following:

resource "azurerm_network_interface" "networkinterace" {
  name                = "${var.vm_name}-NIC1"
  resource_group_name = azurerm_resource_group.vm_resource_group.name
  location            = azurerm_resource_group.vm_resource_group.location
  ip_configuration { 
    name                          = "IPName"
    subnet_id                     = var.subnet_id
    private_ip_address_allocation = var.ip_address_allocation #You can set this to Static
    private_ip_address            = var.private_ip
    }
  tags                 = var.tags 
}

If the user decides the private_ip_address_allocation value to be "Dynamic", then the need for private_ip_address is not needed. However, if the user decides that the value is "Static" then the value is in fact needed.

My immediate solution was to have the user either place the IP value x.x.x.x if they choose Static, and to place "null" if they choose Dynamic. However, running the plan over and over will state that there will be a change and the IP will be changed to null if apply is ran. This actually doesnt do anything on the NIC itself, but I would like this to be more idempotent and show that no change will be made if Plan is ran. Thoughts?

aseb
  • 274
  • 2
  • 11

1 Answers1

4

You can do that.

I assume there is a variable somewhere called is_dynamic:

variable "is_dynamic" {
     default = true
}

Then in your network interface you can set your private_ip_address as follows:

ip_configuration {
   ...
   private_ip_address = var.is_dynamic ? null : var.private_ip
   ...
   }

Or probably you have "Dynamic" and "Static" as a variable value:

variable "allocation" {
    default = "Dynamic"
}

then you can try something like

ip_configuration {
   ...
   private_ip_address = var.allocation == "Dynamic" ? null : var.private_ip
   ...
   }
Fedor Petrov
  • 990
  • 9
  • 19