terraform - 在 Terraform 中将两个列表组合成一个格式化字符串
问题描述
我需要创建一个字符串参数以通过 local-exec 传递给 aws-cli,因此需要将远程状态的两个列表组合成所需的格式,想不出使用内置插值函数的好方法。
必需的字符串格式
"SubnetId=subnet-x,Ip=ip_x SubnetId=subnet--y,Ip=ip_y SubnetId=subnet-z,Ip=ip_z"
我们在两个单独的列表中有子网和相应的 cidr。
["subnet-x","subnet-y","subnet-z"]
["cidr-x","cidr-y","cidr-z"]
正在考虑我可以使用 cidrhost 函数来获取 IP,但看不到将两个列表格式化为一个字符串的方法。
解决方案
尝试使用formatlist后跟join。
locals {
# this should give you
formatted_list = "${formatlist("SubnetId=%s,Ip=%s", var.subnet_list, var.cidrs_list}"
# combine the formatted list of parameter together using join
cli_parameter = "${join(" ", locals.formatted_list)}"
}
编辑:您将需要使用 anull_resource
将 CIDR 转换为 IP 地址,就像在另一个答案中一样。然后你可以像以前一样构建formatted_list
和cli_parameter
。
locals {
subnet_list = ["subnet-x","subnet-y","subnet-z"]
cidr_list = ["cidr-x","cidr-y","cidr-z"]
# this should give you
formatted_list = "${formatlist("SubnetId=%s,Ip=%s", var.subnet_list, null_resource.cidr_host_convert.*.triggers.value)}"
# combine the formatted list of parameter together using join
cli_parameter = "${join(" ", locals.formatted_list)}"
}
resource "null_resource" "cidr_host_convert" {
count = "${length(locals.cidr_list}"
trigger = {
# for each CIDR, get the first IP Address in it. You may need to manage
# the index value to prevent overlap
desired_ips = "${cidrhost(locals.cidr_list[count.index], 1)}"
}
}