Terraform 计数调用模块输出 (return) 错误

Terraform count calling module output(return) error

我只需要return输出名字和id

root main.tf

# Azure Provider configuration
provider "azurerm" {
  features {}
}

module "rg" {
  source              = "../../modules/rg"
  count               = length(var.resource_groups)
  resource_group_name = var.resource_groups[count.index].name
  tags                = {}
  location            = westus2
  lookup              = false
}

module/rg/main.tf

resource "azurerm_resource_group" "rg" {
    count    = var.lookup == true ? 0 : 1
    name = var.resource_group_name
    location = var.location
    tags = var.tags
}

output "rg_id" {
  description = "The id of the newly created rg"
  value       = azurerm_resource_group.rg[count_index].id # azurerm_resource_group.rg, this statement will work
}

output "rg_name" {
  description = "The name of the newly created rg"
  value       = azurerm_resource_group.rg[count_index].name #  azurerm_resource_group.rg, this statement will work
}

我遇到以下错误:

对资源类型的引用必须后跟至少一个属性访问,指定资源名称。

我认为以下内容应该可以解决您的问题:

output "rg_id" {
  description = "The id of the newly created rg"
  value       = var.lookup == true ? azurerm_resource_group.rg[0].id : null
}

output "rg_name" {
  description = "The name of the newly created rg"
  value       = var.lookup == true ? azurerm_resource_group.rg[0].name : null
}