Terraform - 输出索引和项目

Terraform - Output Index along with item

有没有办法修改此输出代码以在名称中包含索引号?下面的当前代码创建了一个索引为“0”的输出,但理想情况下每个名称都应在其自己的索引中(0、1、2 等)

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "3.1.0"
    }
  }
}

provider "azurerm" {
  features {

  }
}

variable "private_link_scopes" {
  description = "A list of Azure private link scopes."
  type = list(object({
    name                = string
    resource_group_name = string
  }))
}
locals {
  rgs_map = {
    for n in var.private_link_scopes : n.resource_group_name => {
      name = n.resource_group_name
    }
  }
}

data "azurerm_resource_group" "rg" {
  for_each = local.rgs_map
  name     = each.value.name
}

output "list" {
  value = { for index, item in [var.private_link_scopes] : index => item[*].name }
}

这里似乎发生了很多结构变化。这可能是由于其他包袱或依赖于它的原因,但我认为这可以简化。我使用局部变量代替变量,但希望对您有所帮助。

我不确定 splat 运算符是否符合您的要求。这与在该 item 值中获取所有项目名称属性的列表相同,但每个 item 只有一个,所以这看起来很奇怪。

locals {
  scopes = [
    {
      name    = "name_a"
      rg_name = "rg_a"
    },
    {
      name    = "name_b"
      rg_name = "rg_b"
    }
  ]
}

data "azurerm_resource_group" "rg" {
  # I don't see a reason to generate the intermediary map
  # or to build another object in each map value. This is more
  # simple. for_each with an object by name: rg_name
  value = { for scope in local.scopes : scope.name => scope.rg_name }
  name  = each.value
}

output "list" {
  # I don't see a need to use a splat expression here.
  # You can just build a map with the index and the name
  # here directly.
  value = { for i, v in local.scopes : i => v.name }
}

事实上,如果您不需要按名称键控资源组资源,可以进一步简化为:

data "azurerm_resource_group" "rg" {
  for_each = toset([for scope in local.scopes : scope.rg_name])
  name     = each.value
}