I have a module that I’m attempting to find AWS subnets within and then use/return. It’s called like this:
module "smurf_subnet_grp" {
source = "../../modules/networking/subnet_grp_per_az-test"
vpc_id = "${module.networking_uswe2.vpc_id}"
azs = "${local.az_list_uswe2}"
private_subnets = "${var.private_subnets_uswe2}"
}
Code for the module:
variable "azs" { type = "list" }
variable "private_subnets" { type = "list" }
variable "vpc_id" {}
# ========== remove special subnets ==============
locals {
cnt = "${length(var.private_subnets) - 3}"
prv_subs = "${slice(var.private_subnets, 0, local.cnt)}"
}
# ========== get subnet details ==================
data "aws_subnet" "self" {
count = "${length(local.prv_subs)}"
vpc_id = "${var.vpc_id}"
cidr_block = "${local.prv_subs[count.index]}"
}
# ========== get subnets by AZ ===================
locals {
prv_subs0 = "${matchkeys(data.aws_subnet.self.*.id, data.aws_subnet.self.*.availability_zone, list(var.azs[0]))}"
prv_subs1 = "${matchkeys(data.aws_subnet.self.*.id, data.aws_subnet.self.*.availability_zone, list(var.azs[1]))}"
prv_subs2 = "${matchkeys(data.aws_subnet.self.*.id, data.aws_subnet.self.*.availability_zone, list(var.azs[2]))}"
}
# ========== select 1 subnet per AZ ==============
resource "random_shuffle" "prv_sub0" {
input = ["${local.prv_subs0}"]
result_count = 1
}
resource "random_shuffle" "prv_sub1" {
input = ["${local.prv_subs1}"]
result_count = 1
}
resource "random_shuffle" "prv_sub2" {
input = ["${local.prv_subs2}"]
result_count = 1
}
# ========== put selected into 1 list ============
locals {
prv_sub_az = [
"${random_shuffle.prv_sub0.result}",
"${random_shuffle.prv_sub1.result}",
"${random_shuffle.prv_sub2.result}"
]
}
output "prv_subnet_grp" {
value = "${local.prv_sub_az}"
}
Which throws this:
Error: Error refreshing state: 1 error occurred:
* module.smurf_subnet_grp.data.aws_subnet.self: 6 errors occurred:
* module.smurf_subnet_grp.data.aws_subnet.self[5]: data.aws_subnet.self.5: no matching subnet found
* module.smurf_subnet_grp.data.aws_subnet.self[3]: data.aws_subnet.self.3: no matching subnet found
* module.smurf_subnet_grp.data.aws_subnet.self[0]: data.aws_subnet.self.0: no matching subnet found
* module.smurf_subnet_grp.data.aws_subnet.self[1]: data.aws_subnet.self.1: no matching subnet found
* module.smurf_subnet_grp.data.aws_subnet.self[2]: data.aws_subnet.self.2: no matching subnet found
* module.smurf_subnet_grp.data.aws_subnet.self[4]: data.aws_subnet.self.4: no matching subnet found
If I introduce a depends_on for the aws_subnet data provider:
data "aws_subnet" "self" {
count = "${length(local.prv_subs)}"
vpc_id = "${var.vpc_id}"
cidr_block = "${local.prv_subs[count.index]}"
depends_on = ["null_resource.module_depends_on"]
}
It’ll work as expected but then will recreate it every time.