skip to Main Content
resource "azurerm_public_ip" "instance_public_ip" {
  count               = var.assign_public_ip == "true" ? 1 : 0
  name                = "${var.name}-public-ip"
  location            = var.location
  resource_group_name = var.resource_group_name
  allocation_method   = "Dynamic"
}

resource "azurerm_network_interface" "main" {
  name                = "${var.name}-nic"
  location            = var.location
  resource_group_name = var.resource_group_name

  ip_configuration {
    name                          = "${var.name}-NIC-Configuration"
    subnet_id                     = var.subnet_id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.instance_public_ip.id
  }
}

This is my problem I only want to set public_ip_address_id attribute if the azure_rm_public_ip resource is created is this possible?

I’m not sure if this is possible.

2

Answers


  1. There are several methods to accomplish this, but the easiest is probably with the try function:

    public_ip_address_id = try(azurerm_public_ip.instance_public_ip[0].id, null)
    
    Login or Signup to reply.
  2. What I would probably do is the following, since you are using the count meta-argument to create the azurerm_public_ip resource:

    resource "azurerm_public_ip" "instance_public_ip" {
      count               = var.assign_public_ip == "true" ? 1 : 0
      name                = "${var.name}-public-ip"
      location            = var.location
      resource_group_name = var.resource_group_name
      allocation_method   = "Dynamic"
    }
    
    resource "azurerm_network_interface" "main" {
      name                = "${var.name}-nic"
      location            = var.location
      resource_group_name = var.resource_group_name
    
      ip_configuration {
        name                          = "${var.name}-NIC-Configuration"
        subnet_id                     = var.subnet_id
        private_ip_address_allocation = "Dynamic"
        public_ip_address_id          = var.assign_public_ip == "true" ? azurerm_public_ip.instance_public_ip[0].id : null
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search