Q:

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

host 0 = subnet-a
host 1 = subnet-b
host 2 = subnet-c
host 3 = subnet-a (i.e. cycle to the first element).

So for example Python has has itertools.cycle
How to achieve the cycle in Terraform's declarative language?

A:

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.

