向Terraform脚本添加条件布尔值
我试图添加一个名为“DeployNSG”的变量作为真/假布尔值。当我使用“Count”引用NSG资源创建中的变量时,我试图将NSG与Azurerm_网络安全组关联与子网关联,这表示我需要在关联中使用Count索引。。然而,如果我尝试使用元素引用一个项目,它会说如果子网关联中未使用count,则不能使用元素向Terraform脚本添加条件布尔值,terraform,terraform-provider-azure,Terraform,Terraform Provider Azure,我试图添加一个名为“DeployNSG”的变量作为真/假布尔值。当我使用“Count”引用NSG资源创建中的变量时,我试图将NSG与Azurerm_网络安全组关联与子网关联,这表示我需要在关联中使用Count索引。。然而,如果我尝试使用元素引用一个项目,它会说如果子网关联中未使用count,则不能使用元素 resource "azurerm_network_security_group" "ProdNSG" { count = "${var.DeployNSG ? 1 : 0}" na
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}"
}
如果我注释掉关联,则True/False条件有效,因此我相信这就是它被卡住的地方。如果存在一个资源的
计数可能为零的情况,然后,在您引用该资源的任何其他位置,您必须告诉Terraform如何处理其他对象不存在的情况
在这种情况下,如果网络安全组不存在,您似乎根本不需要azurerm\u子网\u网络安全\u组\u关联
资源,因此最简单的答案是对其他资源应用相同的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
}
请注意,我们现在可以在引用azurerm\u network\u security\u group.ProdNSG
时使用count.index
,因为azurerm\u subnet\u network\u security\u group\u association.ServersNSGAssociation
具有与azurerm\u network\u security\u group.ProdNSG>相同的计数值。当一个NSG存在时,count.index
将为0,因此它将选择第一个(也是唯一一个)NSG实例。当不存在NSG时,也不存在NSG附件,因此永远不会计算count.index