Skip to content

Instantly share code, notes, and snippets.

@davidfic
Last active December 15, 2017 14:52
Show Gist options
  • Save davidfic/4e3e5fcd9835e1d6477d0cdbcb284357 to your computer and use it in GitHub Desktop.
Save davidfic/4e3e5fcd9835e1d6477d0cdbcb284357 to your computer and use it in GitHub Desktop.
an example of using count to create N number of subnets without a lot of duplication
module "public_subnets" {
source = "modules/aws_public_subnet"
environment = "${var.environment}"
vpc_id = "${module.vpc.vpc_id}"
vpc_cidr = "${module.vpc.vpc_cidr}"
cidrs = "${var.public_subnets}"
availability_zones = "${join(",", data.aws_availability_zones.available.names)}"
}
resource "aws_subnet" "public" {
count = "${length(split(",", var.cidrs))}"
vpc_id = "${var.vpc_id}"
# Determine the Availability Zone and CIDR block for this Subnet instance
availability_zone = "${element(split(",", var.availability_zones), count.index % length(split(",", var.availability_zones)))}"
cidr_block = "${element(split(",", var.cidrs), count.index)}"
# Default to creating public ip addresses for instances in this Subnet
map_public_ip_on_launch = true
tags {
Name = "public-${var.environment}.${element(split(",", var.availability_zones), count.index )}"
Environment = "${var.environment}"
Service = "public subnet"
}
lifecycle {
create_before_destroy = true
}
}
public_subnets = "10.241.10.0/24,10.241.11.0/24,10.241.12.0/24"
#a better way with a map, but the logic above doesn't reflect it
variable "public_subnets" {
type = "map"
default = {
prod = "10.241.10.0/24,10.241.11.0/24,10.241.12.0/24"
dev = "10.242.10.0/24,10.242.11.0/24,10.242.12.0/24"
stage = "10.243.10.0/24,10.2413.11.0/24,10.2413.12.0/24"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment