Terraform循环用正则提取域名遇匹配错误求助
解决方案
问题根源在于regex函数在字符串不匹配正则模式时会直接抛出错误,而你的循环中没有过滤掉那些处理后不符合^\\..*模式的行(比如domain3.com、domain4.net),导致执行时报错。
推荐用更简洁直接的方式实现需求,先对每行做清理,再过滤出以句点开头的条目:
targets = distinct([ for line in split("\n", file("./prod-files/managed-domain-list-simplified.txt")) : cleaned_line let cleaned_line = trim(line, " \r *") if startswith(cleaned_line, ".") ])
代码说明:
let cleaned_line = trim(line, " \r *"):统一清理每行的首尾空格、回车符和*,把*.domain1.com转换成.domain1.com,同时保留.domain2.com的原样。if startswith(cleaned_line, "."):只保留清理后以句点开头的条目,直接过滤掉domain3.com这类不符合要求的行。distinct:对结果去重,避免重复条目。
如果一定要用正则实现,可以改用regexall函数(无匹配时返回空列表,不会报错),再过滤掉空结果:
targets = distinct([ for line in split("\n", file("./prod-files/managed-domain-list-simplified.txt")) : matches[0] let cleaned_line = trim(line, " \r *") let matches = regexall("^\\..*", cleaned_line) if length(matches) > 0 ])
内容的提问来源于stack exchange,提问作者Mike Dodd
相关产品推荐
相关产品推荐

