Reputation: 145
I retrieve the subnet ids from the dev account to attach NLB to them afterwards. There are two subnets per each AZ. Therefore, I get the "Error creating network Load Balancer: InvalidConfigurationRequest: A load balancer cannot be attached to multiple subnets in the same Availability Zone". I need to filter on the subnet names to exclude certain characters ("-lb-") in the name and only use the ones without the "-lb-". I know Terraform can use for_each argument and toset() function but does it have something like contains or where clauses similar to LINQ?
data "aws_subnet_ids" "dev_subnets" {
vpc_id = data.aws_vpc.dev_account_vpc.id
}
and
resource "aws_lb" "dev_network_load_balancer" {
name = "my-nlb"
internal = true
load_balancer_type = "network"
subnets = data.aws_subnet_ids.dev_subnets.ids
...
}
Upvotes: 1
Views: 1622
Reputation: 16775
Assuming that dev_subnets
provides a list of subnet ids from which some may contain -lb-
substring, others may not. For example:
# Returns ["subnet-1", "subnet-lb-1", "subnet-2", "subnet-lb-2"]
data "aws_subnet_ids" "dev_subnets" {
vpc_id = data.aws_vpc.dev_account_vpc.id
}
In order to filter this list we can do the following:
resource "aws_lb" "dev_network_load_balancer" {
name = "my-nlb"
internal = true
load_balancer_type = "network"
# ["subnet-1", "subnet-2"]
subnets = [for s in data.aws_subnet_ids.dev_subnets.ids : s if replace(s, "-lb-", "") == s]
...
}
There are no advanced filter functions in Terraform as of today. replace(s, "-lb-", "")
will attempt to replace the -lb-
with an empty string which is compared to the original string. If they are equal, it means the original string did not contain -lb-
substring.
Update:
If you want to filter strings which do contain -lb-
substring:
[for s in data.aws_subnet_ids.dev_subnets.ids : s if replace(s, "-lb-", "") != s]
Upvotes: 3