简体   繁体   中英

Use the existing Subnet details instead of creating again while creating Network Interface in Azure using terraform

I'm trying to create network Interface in Azure through terraform using below script :

resource "azurerm_subnet" "internal" {
  name                 = "Subnet1"
  resource_group_name  = "${var.VNetResourceGroup}"
  virtual_network_name = "${var.VNetName}"
  address_prefix       = "10.0.2.0/24"
}

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

  ip_configuration {
    name                          = "ipconfig1"
    subnet_id                     = "${azurerm_subnet.internal.id}"
    private_ip_address_allocation = "dynamic"
  }
}

This script creates the Subnet Subnet1 and assigning that Subnet.id in ipconfiguration .

But if I have to create another network interface again through another .tf file with the same Subnet1 , how to do I get the ${azurerm_subnet.internal.id} value again.

That is if the Subnet is already existing and I do not want to create it, how to I set those values and use them?

EDIT

I have figured out, in powershell this is the script used to determine Subnet id :

$vnetId= "[resourceId("VNetRG",'Microsoft.Network/virtualNetworks', "VNetName")]"
$subnetRef = "[concat($vnetId, '/subnets/', "Subnet1")]"

where VNetRG - resource group of VNet ,
VNetName - Name of VNet ,
Subnet1 - Name of Subnet.

Can anyone tell me what is the equivalent script in terraform?

Use a subnet data source :

data "azurerm_subnet" "subnet1" {
  name                 = "Subnet1"
  virtual_network_name = "${var.VNetName}"
  resource_group_name  = "${var.VNetResourceGroup}"
}

Then reference it in your NIC code with

subnet_id  = "${data.azurerm_subnet.subnet1.id}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM