Search code examples
azureterraform

Terraform create an array/list from a number and a variable with a number of elements


I do have a variable with the first 3 octets of an ip address range, like "172.16.100" and 2 variables with a start ip address (last octet, like 2) and the number of ip address, like 3.

How do I create such a list, so I will get an array/list like:

[ 172.16.100.2, 172.16.100.3, .....]

Or is there a better way to create a range op ip addresses from a starting ip address?

Thanks!


Solution

  • You can use the range function to generate a list of numbers using a start value, a limit value, and a step value:

    range(max)
    range(start, limit)
    range(start, limit, step)
    

    Example

    variable "start_ip_address" {
      type        = string
      description = "The starting IP address in format 'x.x.x' - example '172.16.100'"
      default     = "172.16.100"
    }
    
    variable "start_octet" {
      type        = number
      description = "The starting octet in the IP address."
      default     = 4
    }
    
    variable "ip_count" {
      type        = number
      description = "Number of IP addresses to generate."
      default     = 5
    }
    
    locals {
      ip_addresses = [
        for i in range(var.ip_count) :
        format("%s.%d", var.start_ip_address, i + var.start_octet)
      ]
    }
    
    output "ip_addresses" {
      value = local.ip_addresses
    }
    

    Running terraform plan:

    Changes to Outputs:
      + ip_addresses = [
          + "172.16.100.4",
          + "172.16.100.5",
          + "172.16.100.6",
          + "172.16.100.7",
          + "172.16.100.8",
        ]