Terraform:从列表中检索每个子网网关地址。全球控制点

Terraform: Retrieving each subnet gateway address from a list. GCP

之前回答了一个问题,以帮助从列表中创建一组子网。现在我正在尝试输出每个分配的 ip 地址。

module "subnets" {
  source = "../../../Modules/subnets-test/"
  network_name = module.vpc.network_name
  subnet_region = "europe-west2"

  subnets = {
    lister = "192.2.128.0/18",
    kryten = "192.2.0.0/17",
    rimmer = "192.2.208.0/20",
    cat = "192.2.192.0/20",
    holly = "192.2.224.0/20"
  }
}

我可以成功输出子网列表及其值

output "private_subnets" {
  description = "List of IDs of private subnets"
  value       = ["${module.subnets.subnets}"]
}

给我所有的子网输出(下面的例子)

 "rimmer" = {
    "creation_timestamp" = "2020-06-06T03:13:30.244-07:00"
    "description" = ""
    "gateway_address" = "192.2.208.1"
    "id" = "projects/red-dwarf/regions/europe-west2/subnetworks/rimmer"
    "ip_cidr_range" = "192.2.208.0/20"
    "log_config" = []
    "name" = "rimmer"
    "network" = "https://www.googleapis.com/compute/v1/projects/red-dwarf/global/networks/red-dwarf-vpc"
    "private_ip_google_access" = false
    "project" = "red-dwarf"
    "region" = "europe-west2"
    "secondary_ip_range" = []
    "self_link" = "https://www.googleapis.com/compute/v1/projects/red-dwarf/regions/europe-west2/subnetworks/rimmer"

但现在我只想将网关地址提取为单个输出。但是我试图对模块做的任何事情都会给我一个错误,说列表有 5 个属性。

如何在通过 map(string) 提供属性后从创建的子网中提取属性?

编辑 - 子网模块

resource "google_compute_subnetwork" "subnet" {
  network       = var.network_name
  for_each      = var.subnets
  name         = each.key
  ip_cidr_range = each.value

}

编辑 - 子网输出 - 这可以将所有内容作为一个整体输出。

output "subnets" {
  value       = google_compute_subnetwork.subnet
  description = "The created subnet resources"
}

这是我会做的:

locals {
  subnets = {
    cow = "10.0.208.0/20",
    cat = "10.0.192.0/20",
    dog = "10.0.224.0/20"
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_vpc" "myvpc" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "subnet" {
  vpc_id     = aws_vpc.myvpc.id
  for_each   = local.subnets
  cidr_block = each.value
  tags       = { Name = each.key }
}

output "subnets" {
  value = aws_subnet.subnet
}

output "subnets_arn" {
  value = { for k, v in aws_subnet.subnet : k => v.arn }
}

关键是for循环:
value = { for k, v in aws_subnet.subnet : k => v.arn }
这将创建一个新对象,其键名和值是我们想要的 属性。

应用的 terraform 输出是:

subnets_arn = {
  "cat" = "arn:aws:ec2:us-east-1:841836440307:subnet/subnet-046fff167cdc81e9f"
  "cow" = "arn:aws:ec2:us-east-1:841836440307:subnet/subnet-00217a1ec0531d2c6"
  "dog" = "arn:aws:ec2:us-east-1:841836440307:subnet/subnet-0ac82ef0fd87bcee2"
}



在我的例子中,我使用的是 AWS (这是我现在可以访问的) 但同样应该转化为 GCP,只需使用 属性你需要,有根据的猜测应该是这样的:

output "subnets_gateway_address" {
  value = { for k, v in aws_subnet.subnet : k => v.gateway_address }
}