在 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,但看不到将两个列表格式化为一个字符串的方法。

尝试使用格式列表,然后加入。

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_listcli_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)}"
   }
}

其中一个在工作的人想出了这个,

 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

最新更新