'How to get the list of subnets in Terraform
I'm new in terrform and I spent too much time for searching how to get the list of the subnets.
I have two modules : VPC and subnet.
I successfully created the VPC and the subnet resources.
Then, I created a route table resource for the VPC that takes as attribute the vpc_id.
After that I need to link this route table by assigning values to two attributes : subnet_id and route_table_id.
So, I have one VPC that contains 4 subnets in a specific AZ.
When I created the 4 subnets, I used the for_each attribute to make things dynamic.
Now, I would like to create route table link resources to link the 4 subnets that I have created with the route table. So I need to get the list of the subnet created and use the for_each attribute.
Here is the code
main.tf:
module "vpc_fondation_services" {
source = "./modules/vpc"
vpc_name = "vpc_services"
ip_range = "10.221.0.128/26"
}
module "subnet_nominal" {
source = "./modules/subnet"
for_each = local.subnets_nominal
subnet_name = each.key
ip_range = each.value
subregion_name = local.nominal_az
net_id = module.vpc_fondation_services.net_id
}
module "route_table_vpc_fondation_service" {
source = "../network_security/modules/route_table"
route_table_name = "route_table_vpc_fondation_service"
net_id = module.vpc_fondation_services.net_id
}
resource "outscale_route_table_link" "route_table_link" {
for_each = toset([ for subnet in module.subnet_nominal : subnet])
subnet_id = each.value.subnet_id
route_table_id = module.route_table_vpc_fondation_service.route_table_id
}
main.tf of the subnet module
resource "outscale_subnet" "subnet" {
net_id = var.net_id
ip_range = var.ip_range
subregion_name = var.subregion_name
tags {
key = "Name"
value = var.subnet_name
}
}
outputs.tf of the subnet module
output "ip_range" {
value = outscale_subnet.subnet.ip_range
}
output "subnet_id" {
value = outscale_subnet.subnet.subnet_id
}
output "state" {
value = outscale_subnet.subnet.state
}
output "available_ips_count" {
value = outscale_subnet.subnet.available_ips_count
}
the variables.tf of the subnet module
variable "net_id" {
description = "The ID of the Net for which you want to create a Subnet"
type = string
}
variable "subnet_name" {
description = "The name of Subnet"
type = string
}
variable "subregion_name" {
description = "The AZ where subnet need to be"
type = string
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
