![如何创建对现有子网的服务委托?](https://linux22.com/image/774150/%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BA%E5%AF%B9%E7%8E%B0%E6%9C%89%E5%AD%90%E7%BD%91%E7%9A%84%E6%9C%8D%E5%8A%A1%E5%A7%94%E6%89%98%EF%BC%9F.png)
以下代码将在创建子网时创建服务。有没有办法创建对现有子网的委托?主要目的是,以下代码将为策略 Deny-Subnet-Without-Nsg 创建错误。因此,直接在 vnet 块中创建此子网。
resource "azurerm_subnet" "example" {
virtual_network_name = azurerm_virtual_network.aksvnet.name
name = "aks-postgres-subnet"
resource_group_name = azurerm_resource_group.aks_rg.name
address_prefixes = ["10.230.2.0/24"]
service_endpoints = ["Microsoft.Storage"]
delegation {
name = "fs"
service_delegation {
name = "Microsoft.DBforPostgreSQL/flexibleServers"
actions = [
"Microsoft.Network/virtualNetworks/subnets/join/action",
]
}
}
depends_on = [azurerm_virtual_network.aksvnet, azurerm_network_security_group.example]
}
下面的代码没有添加服务委托的选项。
resource "azurerm_virtual_network" "aksvnet" {
name = "aks-network"
location = azurerm_resource_group.aks_rg.location
resource_group_name = azurerm_resource_group.aks_rg.name
address_space = ["10.0.0.0/8"]
subnet {
name = "aks-default-subnet"
address_prefix = "10.240.0.0/16"
security_group = azurerm_network_security_group.example.id
}
subnet {
name = "aks-postgres-subnet"
address_prefix = "10.230.2.0/24"
security_group = azurerm_network_security_group.example.id
}
}
因此,我想先像上面一样创建一个子网,然后再应用服务委托。怎么做?
答案1
有点晚了,但我必须自己解决这个问题,然后偶然发现了这篇文章。
我通过利用解决了这个问题AzAPI 提供程序修补子网。
简而言之:使用子网数据源获取id并进行修补:
data "azurerm_subnet" "subnet" {
name = "my-subnet"
virtual_network_name = "my-vnet"
resource_group_name = "network-rg"
}
/*
NB: Delegation isn't removed on destroy. It does however resolve delta if the delegation is manually removed from the subnet.
Beware of race condition with azurerm_subnet.delegation[] if it's managed by Terraform somewhere else -> in that case: lifecycle { ignore_changes = [ delegation ] }
*/
resource "azapi_update_resource" "patch" {
type = "Microsoft.Network/virtualNetworks/subnets@2022-05-01"
resource_id = data.azurerm_subnet.subnet.id
body = jsonencode({
properties = {
delegations = [
{
name = "aci-delegation"
properties = {
serviceName = "Microsoft.ContainerInstance/containerGroups"
actions = ["Microsoft.Network/virtualNetworks/subnets/action"]
}
}
]
}
})
}
答案2
我不知道为什么 Terraform 不允许你在使用嵌套选项时在子网中添加委托,ARM 规格因为这确实包括委派,所以您可能需要向 Terraform 提出一个错误来添加它。
也就是说,您不能让 Terraform 更新它之前创建的资源,因此唯一的方法是使用 local_exec 块运行某些 PowerShell 或 Azure CLI 来添加委派。
另一种选择是使用 Terraform 中的 ARM 模块让其运行创建 vNet 的 ARM 模板,但这样一来,您就会失去 Terraform 的很多好处。