Error: Cycle: azurerm_network_interface.nic, azurerm_virtual_machine.vm

[root@terraformvm terraform]# terraform validate
Error: Cycle: azurerm_network_interface.nic, azurerm_virtual_machine.vm

Getting above error while creating VM using existing resources like Resource grp,vnet,subnet,image,storage account.

[root@terraformvm terraform]# cat main.tf
#Existing Resource Group
resource “azurerm_resource_group” “rg” {
name = “TerraformDemo-RG”
location = “EAST US2”
}

#Existing virtual network
resource “azurerm_virtual_network” “vnet” {
name = “TerraformDemo-vnet”

address_space = [“10.0.0.0/16”]

location = “eastus2”

resource_group_name = “TerraformDemo-RG”
}

#Existing subnet
resource “azurerm_subnet” “snet” {
name = “TerraformDemo-subnet”
resource_group_name = “TerraformDemo-RG”
virtual_network_name = “TerraformDemo-vnet”

address_prefix = “10.0.1.0/24”

}

#Existing Network Security Group and rule
resource “azurerm_network_security_group” “nsg” {
name = “TerraformDemo-nsg”
location = “eastus2”
resource_group_name = “TerraformDemo-RG”
}

#Create virtual machine
resource “azurerm_virtual_machine” “vm” {
name = “TerraformDemo-vm1”
location = “eastus2”
resource_group_name = “TerraformDemo-RG”
network_interface_ids = [azurerm_network_interface.nic.id]
vm_size = “Standard_B1ms”

storage_os_disk {
    name              = "myOsDisk"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "Standard_LRS"
}

storage_image_reference {
id = data.azurerm_image.custom.id
}

os_profile {
computer_name = “TerraformDemo-vm1”
admin_username = “azureuser”
admin_password = “Mobiledoc$12”
}

os_profile_linux_config {
disable_password_authentication = false
}

boot_diagnostics {
enabled = “true”
storage_uri = azurerm_storage_account.storageaccount.primary_blob_endpoint
}
}

Create public IPs

resource “azurerm_public_ip” “pip” {
name = “myPublicIP”
location = “eastus2”
resource_group_name = “TerraformDemo-RG”
allocation_method = “Dynamic”

tags = {
    environment = "Terraform Demo"
}

}

Create network interface

resource “azurerm_network_interface” “nic” {
name = azurerm_virtual_machine.vm.name-nic
location = “eastus2”
resource_group_name = “TerraformDemo-RG”
network_security_group_id = azurerm_network_security_group.nsg.id

ip_configuration {
    name                          = azurerm_virtual_machine.vm.name-nic-config
    subnet_id                     = azurerm_subnet.snet.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.pip.id
}

tags = {
    environment = "Terraform Demo"
}

}

Hi @vijayraje23,

This issue with your Cycle is due to your Nic relying on the name of the VM to create and your VM relying on the Nic to create.

If you try to create the Nic in it’s own right you will see that it can’t, as it doesn’t know the name of the VM.

Try giving the Nic a Static name without relying on interpolating the VM name.