Reputation: 2011
I've a list of string and I want to ignore certain elements in that list. For example my list
variable domain_names = {
type = list(string)
}
domain_names = ["foo.com","*.foo.com","*.foo2.com","bar.co.in"]
output = [ "foo.com","bar.co.in"]
I want to ignore anything that starts with * and create a new list out of it. How can i achieve this?
I was trying to make this module more robust to handle multiple domain names
locals {
distinct_domain_name = distinct(var.domain_names)
}
resource "aws_acm_certificate" "main" {
count = length(local.distinct_domain_name)
domain_name = local.distinct_domain_name[count.index]
subject_alternative_names = [slice(var.domain_names, 1, length(var.domain_names))]
validation_method = var.validation_method
tags {
Name = local.distinct_domain_name[count.index]
owner = "xxx"
terraform = "true"
}
}
Upvotes: 2
Views: 3427
Reputation: 74109
When our goal is to filter a list, the usual place to start is a for
expression with an if
clause. That allows us to make a decision for each element, but raises the question of what expression to use to make that decision.
For the question of "how can we detect if a string has a particular prefix?" I think there are at least a few different ways to get that done but probably the most concise would be to use a regular expression, via regexall
, and return true if there is at least one match:
length(regexall("^\\*\\.", domain_name)) > 0
I used regexall
rather than regex
here because regex
is defined to return an error if there is no match -- it expects at least one -- whereas regexall
lets us handle the zero-matches case ourselves.
Combining that with a for
expression would give us the following:
[ for domain_name in var.domain_names : domain_name if length(regexall("^\\*\\.", domain_name)) > 0 ]
The above produces a list of the ones that do have *.
as a prefix. We can negate that expression to produce the opposite subset:
[ for domain_name in var.domain_names : domain_name if length(regexall("^\\*\\.", domain_name)) == 0 ]
Upvotes: 4