GREP从阵列中terraform值和所述的发生在terraform计数

时间:2019-01-29 20:20:51

标签: terraform

尝试在多个vpc中设置多个子网 什么是插值语法,用于过滤关键字的出现次数并将其设置为terraform的计数

tfvars文件格式为

"subnets"
        "0:10.3.0.0/24:private",
        "0:10.3.1.0/24:private",
        "1:10.3.2.0/24:public",
        "1:10.3.3.0/24:private"
  • VPC 0中的2个专用子网
  • 在VPC 1中1个公开,1个私有

计划要有一个用于私有子网的模块,另一个用于公共子网。

VPC由另一个模块创建。

public_subnet/main.tf文件中-计划在tfvars文件中为公共var.subnets发起一个grep计数器,并启动该计数器(在我们的情况1中)并遍历由以下各项生成的vpc_id VPC模块(另一个挑战是如何关联哪个ID和哪个vpc)。

private_subnet/main.tf中-var.subnets中专用关键字的Grep中,启动计数器并遍历vpc_id

我要如何这种需要格式化插序列?

谢谢

1 个答案:

答案 0 :(得分:0)

这是使用terraform 0.12.x实现此目的的一种方法

variable "subnets" {
  default = [
    "0:10.3.0.0/24:private",
    "0:10.3.1.0/24:private",
    "1:10.3.2.0/24:public",
    "1:10.3.3.0/24:private"
  ]
}

locals {
  # return the second element in the array which is the IP/CIDR if the vpc is "0"
  subnets_zero = [
    for subnet in var.subnets:
      split(":", subnet)[1]
      if split(":", subnet)[0] == "0"
  ]
  # return the second element in the array which is the IP/CIDR if the vpc is "1"
  subnets_one = [
    for subnet in var.subnets:
      split(":", subnet)[1]
      if split(":", subnet)[0] == "1"
  ]
}

output "subnets_zero" {
  value = local.subnets_zero
}

output "subnets_one" {
  value = local.subnets_one
}
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

subnets_one = [
  "10.3.2.0/24",
  "10.3.3.0/24",
]
subnets_zero = [
  "10.3.0.0/24",
  "10.3.1.0/24",
]