1
votes

I was trying to test the scenario of handling external changes to existing resources and then syncing my HCL config to the current state in the next apply. I could achieve that using 'taint' for the modified resource, but TF deleted other resources which were deployed during the first 'apply'. Here is the module code for a VNet with 3 subnets(prod,dmz and app) and 3 NSGs associated. And I tested with modifying one of the NSGs but TF deleted all of the subnets-

VNET-

resource "azurerm_virtual_network" "BP-VNet" {

name = var.Vnetname
location = var.location
resource_group_name = var.rgname
address_space = var.vnetaddress
subnet {
    name = "GatewaySubnet"
    address_prefix = "10.0.10.0/27"
}

}

Subnet -

resource "azurerm_subnet" "subnets" {
count = var.subnetcount
name = "snet-prod-${lookup(var.snettype, count.index, "default")}-001"
address_prefixes = ["10.0.${count.index+1}.0/24"]
resource_group_name = var.rgname
virtual_network_name = azurerm_virtual_network.BP-VNet.name

}

NSGs-

    resource "azurerm_network_security_group" "nsgs" {
count = var.subnetcount
name = "nsg-prod-${lookup(var.snettype, count.index, "default")}"
resource_group_name = var.rgname
location = var.location
--------
}

BastionSubnet-

    resource "azurerm_subnet" "bastionsubnet" {
  name = "AzureBastionSubnet"
  virtual_network_name = azurerm_virtual_network.BP-VNet.name
  resource_group_name = var.rgname
  address_prefixes = [ "10.0.5.0/27" ]
}

The end result of second apply is -

enter image description here

With just Gateway subnet. It should not have deleted rest of the 4 subnets. Why is this happening?

1
About "I tested with modifying one of the NSGs", What's the specific process that you did? - Nancy Xiong
Changed the priority of one of the inbound rules. After second apply, it was reverted back to the value mentioned in the HCL config. - Anshul Srivastava
Terraform run apply based on a template code from the last terraform.tfstate file. Have you checked the terraform.tfstate file before you re-run apply? - Nancy Xiong
Yes. In the state file, I could see all the resources as expected - Anshul Srivastava
I think I have reproduced your issue. Did you change the priority of one of the inbound rules in the NSG that using count, then you taint that nsg, then run terraform apply? - Nancy Xiong

1 Answers

1
votes

The solution may confuse you. You can separate the GatewaySubnet from the azurerm_virtual_network block into an azurerm_subnet block. The code looks like this:

resource "azurerm_subnet" "gateway" {
  name = "GatewaySubnet"
  resource_group_name = var.rgname
  virtual_network_name = azurerm_virtual_network.BP-VNet.name
  address_prefixes = ["10.0.10.0/27"]
}

I don't know the certain reason, but it solves your issue.