我正在尝试添加一个名为“ DeployNSG”的变量作为true / false布尔值。当我使用'Count'在NSG的资源创建中引用变量时,然后我尝试将NSG与Azurerm_Network_security_group_association与子网关联,这就是说我需要在关联中使用count索引。并使用元素来引用项目,它表示如果子网关联中未使用count,则不能使用元素。
resource "azurerm_network_security_group" "ProdNSG" {
count = "${var.DeployNSG ? 1 : 0}"
name = "${var.ProdNSG}"
location = "${var.location}"
resource_group_name = "${azurerm_resource_group.ProdNetworkRG.name}"
security_rule {
name = "AllowRDP"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "3389"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_virtual_network" "ProdVNet" {
name = "${var.ProdVNet}"
resource_group_name = "${azurerm_resource_group.ProdNetworkRG.name}"
address_space = "${var.ProdVNetAddressSpace}"
location = "${var.location}"
}
resource "azurerm_subnet" "ServersSubnet" {
resource_group_name = "${azurerm_resource_group.ProdNetworkRG.name}"
name = "${var.ServersSubnet}"
address_prefix = "${var.ServersSubnetAddressPrefix}"
virtual_network_name = "${azurerm_virtual_network.ProdVNet.name}"
}
resource "azurerm_subnet_network_security_group_association" "ServersNSGAssociation" {
subnet_id = "${azurerm_subnet.ServersSubnet.id}"
network_security_group_id = "${azurerm_network_security_group.ProdNSG.id}"
}
如果我将关联注释掉,则真/假条件有效,因此,我认为这就是问题所在。
答案 0 :(得分:0)
如果在某些情况下一个资源的count
可能为零,那么在您引用该资源的任何其他位置,您必须告诉Terraform如何处理另一个对象不存在的情况。
在这种情况下,如果网络安全组不存在,您似乎根本不需要azurerm_subnet_network_security_group_association
资源,因此最简单的答案是将相同的count
应用于该资源其他资源:
resource "azurerm_network_security_group" "ProdNSG" {
count = var.DeployNSG ? 1 : 0
# ...other arguments as you already have set...
}
resource "azurerm_subnet_network_security_group_association" "ServersNSGAssociation" {
# Create one of this resource only if there is one of the other resource.
count = length(azurerm_network_security_group.ProdNSG)
subnet_id = azurerm_subnet.ServersSubnet.id
network_security_group_id = azurerm_network_security_group.ProdNSG[count.index].id
}
请注意,现在引用count.index
时可以使用azurerm_network_security_group.ProdNSG
,因为azurerm_subnet_network_security_group_association.ServersNSGAssociation
与count
具有相同的azurerm_network_security_group.ProdNSG
值。存在一个NSG时,count.index
将为0,因此它将选择第一个(也是唯一的)NSG实例。如果没有NSG,那么NSG附件也将不存在,因此count.index
将永远不会得到评估。