Find longest common suffix in Terraform? -> 在Terraform中找到最长的公共后缀?

huangapple go评论61阅读模式
英文:

Find longest common suffix in Terraform?

问题

在Terraform中,您可以使用以下方式来找到这些字符串的最长公共后缀:

locals {
  dns_names = [
    "b-1.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com",
    "b-2.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com",
    "b-3.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com",
  ]
}

data "external" "find_common_suffix" {
  program = ["bash", "-c", "echo '${join(",", local.dns_names)}' | rev | awk -F, '{print $1}' | rev"]
}

output "longest_common_suffix" {
  value = data.external.find_common_suffix.result
}

这个Terraform配置将给出这些DNS名称的最长公共后缀,并将其存储在longest_common_suffix输出中。

英文:

I have a string of DNS names seperated by , like this:

b-1.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com,b-2.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com,b-3.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com

I want to find the longest common suffix of these strings, which in this case is .cluster.abcdef.c2.kafka.us-east-1.amazonaws.com

How can I achieve this in Terraform?

答案1

得分: 1

这是一个简单的示例,如果您使用适当的编程语言:

# util.py
import os.path as p
import sys
import json

r_dns_names = sys.argv[1][::-1]
r_split_dns_names = r_dns_names.split(",")

print(json.dumps({"output": p.commonprefix(r_split_dns_names)[::-1]}))
locals {
  s = "b-1.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com,b-2.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com,b-3.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com"
}

data "external" "util" {
  program = ["python3","util.py","${local.s}"]
}

output "dns" {
  value = data.external.util.result.output
}
$ terraform apply -auto-approve
...
Outputs:

dns = ".cluster.abcdef.c2.kafka.us-east-1.amazonaws.com"
英文:

This is simple if you use a proper programming language:

# util.py
import os.path as p
import sys
import json

r_dns_names = sys.argv[1][::-1]
r_split_dns_names = r_dns_names.split(",")

print(json.dumps({"output": p.commonprefix(r_split_dns_names)[::-1]}))
locals {
  s = "b-1.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com,b-2.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com,b-3.cluster.abcdef.c2.kafka.us-east-1.amazonaws.com"
}

data "external" "util" {
  program = ["python3","util.py","${local.s}"]
}

output "dns" {
  value = data.external.util.result.output
}
$ terraform apply -auto-approve
...
Outputs:

dns = ".cluster.abcdef.c2.kafka.us-east-1.amazonaws.com"

huangapple
  • 本文由 发表于 2023年5月13日 23:29:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定