如果我们创建多个aws_instance
资源:
variable "cluster_size" {
type = number
default = 4
}
variable "private_subnets" {
type = list(string)
default = ["subnet-a", "subnet-b", "subnet-c"]
}
resource "aws_instance" "cassandra" {
instance_type = var.instance_type
count = var.cluster_size
ami = var.ami
key_name = var.security_key.name
subnet_id = var.private_subnets[count.index]
}
如您所见,我有3个私有子网,但要运行4台主机。如何在private_subnets
列表中循环浏览?
所以
例如,Python具有itertools.cycle
如何用Terraform的声明性语言实现循环?
答案 0 :(得分:2)
element
function自动执行此操作,并在序列末尾回绕。这几乎是该函数的主要用途,因为他们在此处使用的方括号中引入了切片符号。
variable "cluster_size" {
type = number
default = 4
}
variable "private_subnets" {
type = list(string)
default = ["subnet-a", "subnet-b", "subnet-c"]
}
resource "aws_instance" "cassandra" {
instance_type = var.instance_type
count = var.cluster_size
ami = var.ami
key_name = var.security_key.name
subnet_id = element(var.private_subnets, count.index)
}
或者,您可以使用%
运算符取模,就像在其他编程语言中一样:
variable "cluster_size" {
type = number
default = 4
}
variable "private_subnets" {
type = list(string)
default = ["subnet-a", "subnet-b", "subnet-c"]
}
resource "aws_instance" "cassandra" {
instance_type = var.instance_type
count = var.cluster_size
ami = var.ami
key_name = var.security_key.name
subnet_id = var.private_subnets[count.index % length(var.private_subnets)]
}
当需要环绕时,第一个选项比较常见;不需要环绕时,方括号切片表示法更常见。