range Function
range
generates a list of numbers using a start value, a limit value,
and a step value.
The start
and step
arguments can be omitted, in which case start
defaults
to zero and step
defaults to either one or negative one depending on whether
limit
is greater than or less than start
.
The resulting list is created by starting with the given start
value and
repeatedly adding step
to it until the result is equal to or beyond limit
.
The interpretation of limit
depends on the direction of step
: for a positive
step, the sequence is complete when the next number is greater than or equal
to limit
. For a negative step, it's complete when less than or equal.
The sequence-building algorithm follows the following pseudocode:
Because the sequence is created as a physical list in memory, Terraform imposes an artificial limit of 1024 numbers in the resulting sequence in order to avoid unbounded memory usage if, for example, a very large value were accidentally passed as the limit or a very small value as the step. If the algorithm above would append the 1025th number to the sequence, the function immediately exits with an error.
We recommend iterating over existing collections where possible, rather than
creating ranges. However, creating small numerical sequences can sometimes
be useful when combined with other collections in collection-manipulation
functions or for
expressions.
Examples
The range
function is primarily useful when working with other collections
to produce a certain number of instances of something. For example: