2
votes

I have a VPC cidr in a map variable, which is defined in Terraform. What I am trying to do is to use a specific value in that map variable in order to dynamically create a subnet in Terraform. Any advice how this would be accomplished would be very helpful. Below is how my variables are defined:

VPC CIDR

variable "vpc_cidr" {
  default {
    us-east-1 = "192.1.0.0/16"
    us-west-1 = "192.2.0.0/16"
    us-west-2 = "192.3.0.0/16"
  }
}

AWS Subnet

resource "aws_subnet" "public_subnets" {
  count = "${length(local.availability_zone_names)}"
  vpc_id = "${aws_vpc.vpc.id}"
  cidr_block = "${cidrsubnet("pulling aws vpc cidr from map variable", newbits, netnum)}"
  availability_zone = "${local.availability_zone_names[count.index]}"
  map_public_ip_on_launch = true
}
1

1 Answers

1
votes

To be honest I am not fully sure about your syntax of defining the variable. I'd rather put it like this (although your version might be also correct):

variable "vpc_cidr" {
  type = map
  default = {
    "us-east-1" = "192.1.0.0/16"
    "us-west-1" = "192.2.0.0/16"
    "us-west-2" = "192.3.0.0/16"
  }
}

and then:

  cidr_block = "${cidrsubnet(var.vpc_cidr[YOUR_CURRENT_REGION], newbits, netnum)}"

Not sure if you have YOUR_CURRENT_REGION defined as a variable somewhere. Otherwise you probably need to extract from a data source:

data "aws_region" "current_region" {}

and use current_region instead of YOUR_CURRENT_REGION