目标:我正在尝试使用 Terraform
创建天蓝色资源
我在 main.tf
中使用的代码:
resource "azurerm_subnet" "clientdata_snet" {
count = var.clientdata_subnet_address_space != null ? 1 : 0
name = "ClientDataSubnet"
resource_group_name = var.resource_group_name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["${var.clientdata_subnet_address_space}"]
service_endpoints = var.service_endpoints
}
现在随后想要使用client_snet.id
来创建存储端点
resource "azurerm_private_endpoint" "sa_pe_blob" {
name = "pe-stdlorpcbcntldevwe-blob-${random_string.postfix.result}"
location = var.location
resource_group_name = var.resource_group_name
subnet_id = azurerm_subnet.clientdata_snet.id
我得到的错误是:
Error: Missing resource instance key
│
│ on main.tf line 470, in resource "azurerm_private_endpoint" "sa_pe_blob":
│ 470: subnet_id = azurerm_subnet.clientdata_snet.id
│
│ Because azurerm_subnet.clientdata_snet has "count" set, its attributes must be accessed on specific instances.
│
│ For example, to correlate with indices of a referring resource, use:
│ azurerm_subnet.clientdata_snet[count.index]
然后我在这里引用了一些帖子..我需要使用如下:
subnet_id = azurerm_subnet.clientdata_snet[count.index].id
然后它给了我这个错误:
Error: Reference to "count" in non-counted context
│
│ on main.tf line 470, in resource "azurerm_private_endpoint" "sa_pe_blob":
│ 470: subnet_id = azurerm_subnet.clientdata_snet[count.index].id
│
│ The "count" object can only be used in "module", "resource", and "data" blocks, and only when the "count" argument is set.
真的很困惑,两种方式都给我带来了错误。我只有根模块,没有任何其他模块。有人可以建议什么是正确的方法吗?
最佳答案
如果您使用 count
元参数,则必须使用正确的索引或使用创建第二个资源的相同方式,通过引用相同的变量来决定计数是什么。所以选项是:
resource "azurerm_private_endpoint" "sa_pe_blob" {
name = "pe-stdlorpcbcntldevwe-blob-${random_string.postfix.result}"
location = var.location
resource_group_name = var.resource_group_name
subnet_id = azurerm_subnet.clientdata_snet[0].id # exact index
}
如您所见,subnet_id
现在正在引用之前创建的索引为 0
的资源。要了解使用 count
时对实例的引用如何工作,请查看 [1]。
第二种方法是这样的:
resource "azurerm_private_endpoint" "sa_pe_blob" {
count = var.clientdata_subnet_address_space != null ? 1 : 0
name = "pe-stdlorpcbcntldevwe-blob-${random_string.postfix.result}"
location = var.location
resource_group_name = var.resource_group_name
subnet_id = azurerm_subnet.clientdata_snet[count.index].id # using count.index
}
这样,您将在子网和端点资源之间创建依赖关系。
正如您在这里所看到的,使用 count
创建的资源可以通过指定确切的索引来引用,当只有一个资源时这很好,但当有更多资源并且代码时就困难得多必须重复。另一种方法是将相同的变量与 count
元参数一起使用。
我强烈建议阅读文档以更好地理解 count
元参数。
[1] https://www.terraform.io/language/meta-arguments/count#referring-to-instances
关于terraform - 如何修复 "count"对象只能在 "module"、 "resource"和 "data" block 中使用,并且仅当 "count"参数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72920731/