hashicorp / terraform-provider-azurerm

Terraform provider for Azure Resource Manager
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs
Mozilla Public License 2.0
4.54k stars 4.61k forks source link

[Question] azurerm_subnet/azurerm_virtual_network control what subnets are in vnet #13191

Open kacper2k1lop opened 3 years ago

kacper2k1lop commented 3 years ago

Community Note

Terraform (and AzureRM Provider) Version

Terraform v1.0.4 azurerm v2.74

Affected Resource(s)

azurerm_subnet, azurerm_virtual_network

Expected Behaviour

I want to control what subnets are deployed on my vnet with terrraform, so only subnets configured in my terraform configuration are configured in vnet, no more, no less.

Actual Behaviour

I dont see any possiblity to configure it with this resource azurerm_subnet and when I will configure subnets with resource: azurerm_virtual_network I will not be able to use service endpoints and delegations and others.

Question

Do you see some way to configure it with terraform? Should I put arm template to terraform to handle this issue?

ljluestc commented 1 week ago

provider "azurerm" {
  features {}
}

# Define Virtual Network
resource "azurerm_virtual_network" "vnet" {
  name                = "my-vnet"
  address_space       = ["10.0.0.0/16"]
  location            = "East US"
  resource_group_name = "my-resource-group"
}

# Define Subnet with Service Endpoints and Delegations
resource "azurerm_subnet" "subnet" {
  for_each = {
    subnet1 = {
      name           = "subnet1"
      address_prefix = "10.0.1.0/24"
      service_endpoints = ["Microsoft.Sql"]
      delegations = [{
        name = "delegation-1"
        service_delegation {
          name    = "Microsoft.Sql/servers"
          actions = ["Microsoft.Network/virtualNetworks/subnets/join/action"]
        }
      }]
    }
    subnet2 = {
      name           = "subnet2"
      address_prefix = "10.0.2.0/24"
      service_endpoints = ["Microsoft.Storage"]
      delegations = []
    }
  }

  name                 = each.value.name
  virtual_network_name = azurerm_virtual_network.vnet.name
  resource_group_name  = azurerm_virtual_network.vnet.resource_group_name
  address_prefixes     = [each.value.address_prefix]

  service_endpoints    = each.value.service_endpoints

  delegation {
    name = try(each.value.delegations[0].name, null)
    service_delegation {
      name    = try(each.value.delegations[0].service_delegation.name, null)
      actions = try(each.value.delegations[0].service_delegation.actions, [])
    }
  }

  lifecycle {
    ignore_changes = [service_endpoints]
  }
}