Reputation: 64
I am trying to implement for_each for map of list input variables.
What the output should be is a list of subnets should be created for AZ us-east-1a(3 subnets) and us-east-1b (2 subnets).
Need your help for the below:
MAIN.TF
resource "aws_vpc" "name" {
cidr_block = "192.168.0.0/16"
}
resource "aws_subnet" "name" {
for_each = var.subnetcidr
vpc_id = aws_vpc.name.id
availability_zone = each.key
cidr_block = toset(each.value) //need help here
}
TFVARS FILE
subnetcidr = {
"us-east-1a" = ["192.168.1.0/24","192.168.2.0/24","192.168.0.0/24"]
"us-east-1b" = ["192.168.3.0/24","192.168.4.0/24"]
}
Error:
Error: Incorrect attribute value type
on main.tf line 28, in resource "aws_subnet" "name":
28: cidr_block = toset(each.value)
|----------------
| each.value is tuple with 2 elements
Inappropriate value for attribute "cidr_block": string required.
Any help would be appreciated. TIA!
Upvotes: 2
Views: 2732
Reputation: 64
I was finally able to solve this. Below is how.
resource "aws_vpc" "name" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "name" {
vpc_id = aws_vpc.name.id
for_each = transpose(var.subnet)
availability_zone = each.value[0]
cidr_block = each.key
}
variable subnet {}
subnet = {
"us-east-1a" = ["10.0.0.0/20","10.0.16.0/20","10.0.32.0/20"]
"us-east-1b" = ["10.0.64.0/20","10.0.80.0/20"]
"us-east-1d" = ["10.0.112.0/20","10.0.128.0/20","10.0.144.0/20","10.0.96.0/20"]
}
Upvotes: 0
Reputation: 17664
The error seems clear:
Inappropriate value for attribute "cidr_block": string required
Not sure why you are passing a list...
resource "aws_vpc" "name" {
cidr_block = "192.168.0.0/16"
}
resource "aws_subnet" "name" {
for_each = var.subnetcidr
vpc_id = aws_vpc.name.id
availability_zone = each.key
cidr_block = element(each.value, 0)
}
subnetcidr
variable, go with something like:subnetcidr = {
"192.168.0.0/24" = "us-east-1a"
"192.168.1.0/24" = "us-east-1a"
"192.168.2.0/24" = "us-east-1a"
"192.168.3.0/24" = "us-east-1b"
"192.168.4.0/24" = "us-east-1b"
}
As you can see now the unique cidr blocks are the keys and the zones are the values.
Then in your code we do like this:
resource "aws_vpc" "name" {
cidr_block = "192.168.0.0/16"
}
resource "aws_subnet" "name" {
for_each = var.subnetcidr
vpc_id = aws_vpc.name.id
availability_zone = each.value
cidr_block = each.key
}
Upvotes: 0