DmitrySemenov
DmitrySemenov

Reputation: 10305

Cycle through Terraform list

If we create multiple aws_instance resources:

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]
}

as you can see I have 3 private subnets, but 4 hosts to run. How to cycle through the list of private_subnets?

So

So for example Python has has itertools.cycle

How to achieve the cycle in Terraform's declarative language?

Upvotes: 2

Views: 419

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56839

The element function automatically does this, wrapping around at the end of the sequence. It's pretty much the main use of that function since they introduced the slice notation with square brackets that you're using there.

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

Alternatively, you could take the modulo by using the % operator just like you can in other programming languages:

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)]
}

The first option is more common when needing to wrap around with the square bracket slice notation more common when you don't need to wrap around.

Upvotes: 4

Related Questions