Score:0

How to iterative over public/private subnets in the Terraform VPC module?

br flag

I'm trying to define public and private subnets as input variables to the Terraform vpc module. How can I reference my private/public subnet variables in an iterative statement rather than hard-coding in the "list[x]" elements?

I have the vpc module (only two AZs at the moment) defined in main.tf.

module "vpc" {
  source          = "terraform-aws-modules/vpc/aws"
  name            = "my-vpc"
  cidr            = var.my_cidr

  azs             = ["eu-west-1a", "eu-west-1b"]
  private_subnets = [var.my_private_subnets[0], var.my_private_subnets[1]]
  public_subnets  = [var.my_public_subnets[0], var.my_public_subnets[1]]
  #                      ^
  #                      +--- can these subnets be iterated over in a for_each here?
  ...
}

My subnet input variables are defined like this:

variable "my_cidr" {
  description = "The IPv4 CIDR block for the VPC"
  type        = string
  default     = "10.10.0.0/16"
}

variable "my_private_subnets" {
  type = list
  description = "private subnet within vpc cidr block"
  default = ["10.10.20.0/24", "10.10.30.0/24"]
}

variable "my_public_subnets" {
  type = list
  description = "public subnet within vpc cidr block"
  default = ["10.10.100.0/24", "10.10.200.0/24"]
}
Score:0
mp flag

First update the variables type to list(string)

    variable "my_private_subnets" {
    type = list(string)
    description = "private subnets within vpc cidr block"
    default = ["10.10.20.0/24", "10.10.30.0/24"]
    }

    variable "my_public_subnets" {
    type = list(string)
    description = "public subnets within vpc cidr block"
    default = ["10.10.20.0/24", "10.10.30.0/24"]
    }

Then pass these as variables to module as following:

    module "vpc" {
    source = "terraform-aws-modules/vpc/aws"
    name   = "my-vpc"
    cidr   = "10.6.0.0/16"

    azs = ["eu-west-1a", "eu-west-1b"]
    private_subnets = var.my_private_subnets
    public_subnets  = var.my_public_subnets
    
    }
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.