Deploying subnets in AZs automatically

639 views
Skip to first unread message

Francisco Javier Romero Mendiola

unread,
Sep 13, 2016, 5:06:02 AM9/13/16
to Terraform
I am trying to setting up subnets per AZs within regions. This is my aws_subnet resource:

resource "aws_subnet" "internal" {
  count                   = "${length(split(",", lookup(var.aws_azs, var.region)))}"
  vpc_id                  = "${aws_vpc.main.id}"
  cidr_block              = "${element(var.subnet_int_cidr, count.index)}"
  availability_zone       = "${element((lookup(var.aws_azs,var.region)),count.index)}"
  tags {
    Name    = "${var.subnet_int_name}${count.index + 1}"
  }
}

When I issue "terraform plan" it prints the following error:

$ terraform plan
Error configuring: 2 error(s) occurred:

* lookup: lookup() may only be used with flat maps, this map contains elements of type list in:

${length(split(",", lookup(var.aws_azs, var.region)))}

Could be this a new feature or there is another solution?

Regards.

Francisco Javier Romero Mendiola

unread,
Sep 13, 2016, 5:27:04 AM9/13/16
to Terraform
I achieved if I declare a map with strings and not a map:

variable "aws_azs" {
  description = "AWS Availability Zones"
  default = {
    us-east-1     = "us-east-1a,us-east-1c,us-east-1d"
    eu-west-1     = "eu-west-1a,eu-west-1b,eu-west-1c"
    eu-central-1  = "eu-central-1a,eu-central-1b,eu-central-1c"

Martin Atkins

unread,
Sep 15, 2016, 11:05:13 AM9/15/16
to Terraform
Hi Francisco,

In Terraform 0.7 it's suggested to use the square bracket indexing syntax rather than the element and lookup functions. The type system for functions in Terraform doesn't allow a function's return type to vary based on its input type, so the functions must always return strings.

var.subnet_int_cidr[count.index]
var.aws_azs[var.region]

Since this is a first-class operator in Terraform, it is able to vary on operand type as we need here, and so should achieve what you're looking for I believe.

Francisco Javier Romero Mendiola

unread,
Sep 15, 2016, 11:12:52 AM9/15/16
to Terraform
Thanks for your response Martin.

Where can I find that information about square bracket indexing syntax?

Regards.

Adam Gotterer

unread,
Sep 15, 2016, 11:12:49 PM9/15/16
to Terraform
I was working on something similar today. This is what I ended up with:

variable "private_subnets" {
  description "A list of private subnets"
  default = {
    us-east-1a = "10.0.0.0/19"
    us-east-1b = "10.0.32.0/19"
    us-east-1c = "10.0.64.0/19"
  }
}

resource "aws_subnet" "private" {
  vpc_id = "${aws_vpc.default.id}"
  cidr_block = "${lookup(var.private_subnets, element(keys(var.private_subnets), count.index))}"
  availability_zone = "${element(keys(var.private_subnets), count.index)}"
  count = "${length(keys(var.private_subnets))}"

  tags {
    Name = "${var.name}: ${element(keys(var.private_subnets), count.index)} (private)"
  }
}

Hope that helps!

Adam
Reply all
Reply to author
Forward
0 new messages