简体   繁体   中英

Output of values from multiple subnets created using a for_each loop

I've created some subnets using a for_each loop like below

main.tf in child module

resource "azurerm_subnet" "obc_subnet" {
name                  = var.subnet_name
address_prefixes      = var.address_prefixes
resource_group_name   = var.resource_group_name
virtual_network_name  = var.vnet_name
}

main.tf in root module

module "deploy_subnet" {
  source              = "./modules/azure_subnet"
  for_each              = var.prefix
  subnet_name           = each.value["name"]
  address_prefixes      = [each.value["cidr"]]
  subscription_id       = var.subscription_id
  resource_group_name   = var.resource_group_name
  region                = var.region
  vnet_name             = var.vnet_name
}

variables.tf in root module

variable "prefix" {
  type  = map(object({
    name = string
    cidr = string
  }))
  default = {
    sub-1 = {
      name = "aks-sn"
      cidr = "10.0.1.0/24"
    }
    sub-2 = {
      name = "postgres-sn"
      cidr = "10.0.2.0/24"
    }
    sub-3 = {
      name = "keyvault-sn"
      cidr = "10.0.3.0/24"
    }
  }
}

Thats all working fine except when I try and output the values associated with the 3 subnets (id for example)

I'm trying to use the for k syntax in the output but I'm not really understanding how it should look.

I have the below in my output.tf of the child module

output "subnet_ids" {
  value = tomap({
    for k, subnets in azurerm_subnet.obc_subnet : k => subnets.id
      })
}

I wasnt really sure how to approach the output.tf in my root module so I left it as is

output "subnet_id" {
  value = module.deploy_subnet.subnet_id
}

I'm getting an error that the value has no attributes

Error: 

Unsupported attribute
  on modules/azure_subnet/output.tf line 3, in output "subnets_id":
   3:     for k, subnets in azurerm_subnet.obc_subnet : k => subnets.is

This value does not have any attributes.

Close, but the other way around.

The azurerm_subnet resource in the child module is not a collection, so the output there should be just:

output "subnet_id" {
  value = azurerm_subnet.obc_subnet.id
}

But in the root module you have the collection of child modules. Thus for example:

output "subnet_ids" {
  value = {
    for k, subnet in module.deploy_subnet : k => subnet.subnet_id
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM