0
votes

I'm trying to create AWS vpc environment with public and private subnet which I create with "template_file", however, I'm facing issues with defining the public and private subnets inside the VPC module.

I'v generated my subnets using:

data "template_file" "cidrsubnets" {
  count = var.subnet_count[terraform.workspace]

  template = "$${cidrsubnet(vpc_cidr,8,current_count)}"

  vars = {
    vpc_cidr      = var.network_address_space[terraform.workspace]
    current_count = count.index
  }
}

Inside the VPC module, the above code adds all my subnets into public subnets (works):

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"
  name   = "${local.prefix}-vpc"

  cidr            = var.network_address_space[terraform.workspace]
  azs             = slice(data.aws_availability_zones.available.names, 0, var.subnet_count[terraform.workspace])
  public_subnets  = data.template_file.cidrsubnets[*].rendered
  private_subnets = []

  create_database_subnet_group = false
  enable_dns_hostnames         = true
  enable_nat_gateway           = true
  enable_s3_endpoint           = true
  enable_dynamodb_endpoint     = true

  tags = local.common_tags
}

However, I want to add the even subnets in the list to the public subnets and the odd subnets in the list to the private subnets. I still haven't split the subnets into private and public automatically (that what I need), but tried to add specific elements inside the lists and got the error above: enter image description here

Can you help with this? Thank you for the response.

1
Please update your question with what you have tried and the error message.Matt Schuchard
Done. I added the error I get when manually split my subnets into public subnets and private subnets. Yet, haven't succeeded to do that automatically by splitting even and odd places inside the subnets list to private and public subnets.Yuval Podoksik

1 Answers

0
votes

using a template_file data source here seems overly complicated. I guess what you want to achieve is something like the following (using locals for better readability) [untested]:

locals {
  cidr    = var.network_address_space[terraform.workspace]
  netnums = range(var.subnet_count[terraform.workspace])
}

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  ....
  cidr           = local.cidr
  public_subnets = [for i in local.netnums : cidrsubnet(local.cidr, 8, i)]
  ....
}

netnums will be an array of numbers starting at 0.. see range() terraform function on how to start at a different number.