Hi,
I’d like to create VPC_peering using a nested map of VPC names and IDs as follows:
Variable Definition:
variable vpc_details {
type = map(object({
owner_id = string
vpc_id = string
}))
description = ""
}
tfvars file:
vpc_details = {
vpc1 = {
owner_id = "<owner_id>"
vpc_id = "<vpc_id"
}
vpc2 = {
owner_id = "<owner_id>"
vpc_id = "<vpc_id"
}
}
Resource (which doesn’t work)
resource "aws_vpc_peering_connection" "VPCs_to_peer" {
for_each = var.vpc_details
peer_owner_id = each.key.owner_id
peer_vpc_id = each.key.vpc_id
vpc_id = module.vpc.vpc_id
auto_accept = true
tags = {
Name = "${module.vpc.vpc_id}-2target_vpc"
}
accepter {
allow_remote_vpc_dns_resolution = true
}
requester {
allow_remote_vpc_dns_resolution = true
}
}
Can anyone give advice of how to iterate a list of VPCs and have their details connected to them?
A working solution which I think is less powerful is:
Variable Definition:
variable aws_owner_id {
default = "<our id>"
}
variable peered_vpcs {
type = map
}
tfvars file:
peered_vpcs = {
vpc1 = "<vpc1_id>"
vpc2 = "<vpc2_id>"
}
Resource:
resource "aws_vpc_peering_connection" "VPCs_to_peer" {
for_each = var.peered_vpcs
peer_owner_id = var.aws_owner_id
peer_vpc_id = each.value
vpc_id = module.vpc.vpc_id
auto_accept = true
tags = {
Name = "${module.vpc.vpc_id}-2${each.key}"
}
accepter {
allow_remote_vpc_dns_resolution = true
}
requester {
allow_remote_vpc_dns_resolution = true
}
}
Hi @orarnon!
You showed an example which doesn’t work, but you didn’t say what happened when you tried it. If Terraform showed an error message when given that configuration, could you please share that error message? Otherwise, if Terraform just did something different than what you expected, it would be helpful to know what you wanted it to do and what it did instead.
Hi,
This is the result:
Error: Unsupported attribute
on main.tf line 55, in resource "aws_vpc_peering_connection" "VPCs_to_peer":
55: peer_owner_id = each.key.owner_id
This value does not have any attributes.
Error: Unsupported attribute
on main.tf line 56, in resource "aws_vpc_peering_connection" "VPCs_to_peer":
56: peer_vpc_id = each.key.vpc_id
This value does not have any attributes.
The each.key
references here return the string key from the map, like "vpc1"
or "vpc2"
. It looks like you want to access attributes from the values in the map, in which case you should use each.value
instead:
peer_vpc_id = each.value.vpc_id
1 Like
I’ve tried several ways but this is indeed the simplest one and looks pretty obvious now that you’ve mentioned it.
Thanks a lot!