Terraform Range function to start from 1 instead of 0

Is there a way to make the range function of terraform start from 1 instead of 0 or any other function or way to achieve the end result.

Let’s say I have code as seen below.

variable "nodes" {
  default = 1
}

locals {
  node_range = range(var.nodes)
}

This returns the following output.

[
  0
]

I would like to be able to get the output as shown below (pseudo code)

[
  1
]

The reason I would like to have it this way is that, we cannot use count.index + 1 in for_each resources. Hence, if I get the list from range function which starts from 1, then I can simply use it in other places.

I have name tags that should start from myec2instance01, myec2instance02 …etc. But if we get the range start from 0 then we get the numbering of tag from 00 (myec2instance00).

Any other way to achieve the end result is also accepted as a valid solution.

Hi @limratechnologies,

The range function takes either one, two, or three arguments, with each additional argument overriding what would otherwise be a default behavior.

The two-argument form allows you to specify both the start index (inclusive) and the end index (exclusive):

locals {
  node_range = range(1, var.nodes + 1)
}

Note that we need to say var.nodes + 1 as the “end” here because the range function will stop before appending the number that was greater than or equal to the final bound.

1 Like