Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform: Trying to create a range of subnet cidrs using a list, but getting error "string required"

Created a list of ranges as per below

subnet_names = ["subnet-lister", "subnet-kryten", "subnet-rimmer", "subnet-cat", "subnet-holly",]
subnet_cidrs = ["192.2.128.0/18", "192.2.0.0/17", "192.2.208.0/20", "192.2.192.0/20", "192.2.224.0/20",]

With this in the subnets.tf

resource "google_compute_subnetwork" "subnet" {
  name          = "${var.subnet_names}-subnet"
  ip_cidr_range = var.subnet_cidrs
  network       = var.network_name
  region        = var.subnet_region

And the below in variables.tf (for the module)

variable "subnet_names" {
  description = "The name to use for Subnet "
  type        =  list(string)
}

variable "subnet_cidrs" {
  description = "The cidr range for for Subnets"
  type        = list(string)
}

But getting the following message from Terraform.

Error: Incorrect attribute value type

  on ..\..\..\Test-Modules\red\dwarf\subnets.tf line 3, in resource "google_compute_subnetwork" "subnet":
   3:   ip_cidr_range = var.subnet_cidrs

Inappropriate value for attribute "ip_cidr_range": string required.

I'm pretty new to this, can you help me work out what I am going wrong. I've seem someone else use a list for the cidr range (mind you that was for AWS). Does GCP not support this?

like image 217
Pydam Avatar asked Jan 25 '23 00:01

Pydam


1 Answers

It looks like what you're trying to do is actually create several subnets. For that, you should use a map variable and a loop.

variable "subnets" {
    type = map(string)
}

resource "google_compute_subnetwork" "subnet" {
  for_each      = var.subnets
  name          = each.key
  ip_cidr_range = each.value
  ...
}

Then you can provide the subnets like:

subnets = {
    subnet-lister = "192.2.128.0/18",
    subnet-kryten = "192.2.0.0/17",
    ...
}
like image 173
Ben Whaley Avatar answered Feb 11 '23 22:02

Ben Whaley