下面给出的脚本可以正常工作。但是问题是,当我第二次给Terraform应用时,它会断开NSG与子网的关联。当我再次申请时,它与子网关联。我的代码有问题吗?或者这行代码实际上可以解决我的问题。
network_security_group_id =
"${element(azurerm_network_security_group.NetworkSG.*.id,count.index)}"
下面的代码是我的main.tf:
resource "azurerm_subnet" "Subnet" {
count = "${length(var.Subnet_name)}"
name = "${var.Subnet_name[count.index]}"
virtual_network_name = "${azurerm_virtual_network.Vnet.name}"
resource_group_name =
"${azurerm_resource_group.ResourceGroup.name}"
address_prefix =
"${element(var.Subnet_range[var.Subnet_name[count.index]], 0)}"
}
resource "azurerm_network_security_group" "NetworkSG" {
count = "${length(var.Subnet_name)}"
name =
"${element(var.Subnet_range[var.Subnet_name[count.index]], 1)}"
location =
"${azurerm_resource_group.ResourceGroup.location}"
resource_group_name = "${azurerm_resource_group.ResourceGroup.name}"
}
resource "azurerm_subnet_network_security_group_association"
"NetworkSGassociation" {
count= "${length(var.Subnet_name)}"
subnet_id = "${element(azurerm_subnet.Subnet.*.id, count.index)}"
network_security_group_id =
"${element(azurerm_network_security_group.NetworkSG.*.id,count.index)}"
}
下面是我的.tfvars文件:
Subnet_name= ["SCB-Sub1","SCB-Sub2","SCB-Sub3"]
Subnet_range =
{
SCB-Sub1= ["10.10.0.0/24","SCB-nsg1"]
SCB-Sub2= ["10.10.1.0/24","SCB-nsg2"]
SCB-Sub3= ["10.10.2.0/24","SCB-nsg3"]
}
这是我使用Terraform Plan时得到的输出:
azurerm_subnet.Subnet[1]: Modifying... (ID:
/subscriptions/0000-...tualNetworks/SCB_vnet/subnets/SCB-Sub3)
network_security_group_id: "/subscriptions/0000/resourceGroups/SCB-
rg/providers/Microsoft.Network/networkSecurityGroups/SCB-nsg3" => ""