Azure apply - subnet not found, but is indeed there

Working on an Azure Bastion module. It fails here:

data "azurerm_subnet" "subnet_data" {
  name                 = "${var.subnet_name}"
  virtual_network_name = "${var.virtual_network_name}"
  resource_group_name  = "${var.resource_group_name}"
}

with the following error:

Error: Error: Subnet “AzureBastionSubnet” (Virtual Network “security-vnet” / Resource Group “security-network-rg”) was not found

Thing is, the subnet does indeed exist. Running apply a second time succeeds. My guess is that Azure returns that it has completed creating the subnet but is in fact still in the process of creating it. Seems odd to me since subnets are created quickly and the actual creation of the subnet is far earlier in my scripting.

I seem to be hitting issues like this fairly often. Is there a best practice on placement of resource elements or a method to slow down the execution? I also get an error on destroy that a resource is still in use when it has been deleted already.

Thanks.

The fix for this was to move creation of the subnet for bastion into the same module that creates bastion. Not sure why that would make a difference but seems things within the same module are controlled/tracked differently?

This problem generally surfaces because of your current selected or scoped subscription. Since Terraform is likely using your CLI state, it’s expecting the currently selected subscription to include what you’re looking for. If that’s not accurate, you need to set the context within the azurerm provider (additional if necessary).