我需要创建一个字符串参数以通过local-exec传递给aws-cli,因此需要将来自远程状态的两个列表组合成所需的格式,无法想到使用内置插值函数实现此目的的好方法
必需的字符串格式
"SubnetId=subnet-x,Ip=ip_x SubnetId=subnet--y,Ip=ip_y SubnetId=subnet-z,Ip=ip_z"
我们在两个单独的列表中有子网和相应的子容器。
["subnet-x","subnet-y","subnet-z"]
["cidr-x","cidr-y","cidr-z"]
以为我可以使用cidrhost函数获取IP,但是看不到将两个列表格式化为一个字符串的方法。
答案 0 :(得分:2)
尝试使用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)}"
}
编辑:您将需要使用null_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)}"
}
}
答案 1 :(得分:1)
一个工作的人想到了这个,
variable "subnet_ids" {
default = ["subnet-345325", "subnet-345243", "subnet-345234"]
}
variable "cidrs" {
default = ["10.0.0.0/24", "10.0.1.0/24", "10.0.2.0/23"]
}
resource "null_resource" "subnet_strings_option_one" {
count = "${length(var.subnet_ids)}"
triggers {
value = "SubnetId=${var.subnet_ids[count.index]},Ip=${cidrhost(var.cidrs[count.index],11)}"
}
}
output "subnet_strings_option_one" {
value = "${join("",null_resource.subnet_strings_option_one.*.triggers.value)}"
}
这给出了以下输出
null_resource.subnet_strings_option_one[1]: Creating...
triggers.%: "" => "1"
triggers.value: "" => "SubnetId=subnet-345243,Ip=10.0.1.11"
null_resource.subnet_strings_option_one[2]: Creating...
triggers.%: "" => "1"
triggers.value: "" => "SubnetId=subnet-345234,Ip=10.0.2.11"
null_resource.subnet_strings_option_one[0]: Creating...
triggers.%: "" => "1"
triggers.value: "" => "SubnetId=subnet-345325,Ip=10.0.0.11"
null_resource.subnet_strings_option_one[2]: Creation complete after 0s (ID: 852839482792384695)
null_resource.subnet_strings_option_one[1]: Creation complete after 0s (ID: 5439264637705543321)
null_resource.subnet_strings_option_one[0]: Creation complete after 0s (ID: 1054498808481879719)
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
Outputs:
subnet_strings_option_one = SubnetId=subnet-345325,Ip=10.0.0.11 SubnetId=subnet-345243,Ip=10.0.1.11 SubnetId=subnet-345234,Ip=10.0.2.11