gpt4 book ai didi

Terraform - 如何获取在 for_each block 中创建的资源的引用

转载 作者:行者123 更新时间:2023-12-04 16:25:35 62 4
gpt4 key购买 nike

我在下面的代码中在 for_each 块中创建了 vnet:

provider "azurerm" {
features {}
}

variable "vnets" {
type = map(object({
name = string
address_space = list(string)
}))
default = {
"vnet1" = {
"name" = "vnet1",
"address_space" = ["10.0.0.0/16"]
},
"vnet2" = {
"name" = "vnet2",
"address_space" = ["10.1.0.0/16"]
}
}
}

resource "azurerm_resource_group" "vnets" {
name = "vnets"
location = "WestEurope"
}

resource "azurerm_virtual_network" "virtual_network" {
for_each = var.vnets
name = each.value.name
location = "West Europe"
resource_group_name = azurerm_resource_group.vnets.name
address_space = each.value.address_space
}

一切都符合计划,将创建虚拟网络,
但问题是如何从 for_each 块中获取创建的资源?
当我输入命令返回资源列表时:
terraform state list
然后我从控制台得到以下输出:
azurerm_resource_group.vnets
azurerm_virtual_network.virtual_network["vnet1"]
azurerm_virtual_network.virtual_network["vnet2"]
当我想使用引用 azurerm_virtual_network.virtual_network["vnet1"] 在代码中的任何地方使用 vnet1 时,我会收到错误消息。
比如我要查看资源vnet1:
terraform state show azurerm_virtual_network.virtual_network["vnet1"]
我收到这样的错误:
Error parsing instance address: azurerm_virtual_network.virtual_network[vnet1]

This command requires that the address references one specific instance.
To view the available instances, use "terraform state list". Please modify
the address to reference a specific instance.
我尝试了以下命令来访问资源,但它们不起作用:
terraform state show azurerm_virtual_network.virtual_network["vnet1"]
terraform state show 'azurerm_virtual_network.virtual_network["vnet1"]'
terraform state show azurerm_virtual_network.virtual_network[vnet1]
terraform state show azurerm_virtual_network.virtual_network[0]
terraform state show azurerm_virtual_network.virtual_network.vnet1
你知道如何解决吗?

最佳答案

In addition, if you want to show a specific instance in the state file, you can use terraform state show 'azurerm_virtual_network.virtual_network[\"vnet1\"]'


我在使用模块时遇到了同样的问题。上面引用的是正确答案,以下是如何使用模块执行它:
terraform state show 'module.module_name[\"module_instance\"].resource.resource_name[\"resource_instance\"]
例子:
state show 'module.rsm_keyvault_solution_module_resource[\"development\"].azurerm_key_vault.keyvault_module_resource[\"rsm-playground-dev\"]'

关于Terraform - 如何获取在 for_each block 中创建的资源的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65074893/

62 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com