Skip to content

Instantly share code, notes, and snippets.

@li0nel
Created April 10, 2018 09:11
Show Gist options
  • Save li0nel/2b1dd1f90560a5cae144eb8aa9baaa16 to your computer and use it in GitHub Desktop.
Save li0nel/2b1dd1f90560a5cae144eb8aa9baaa16 to your computer and use it in GitHub Desktop.
The beauty of Terraform
# "data" keyword allow you to pull existing resources from your AWS account
# In this case, we pull the list of availability zones from the current AWS region
data "aws_availability_zones" "available" {}
# Local values assign names to expressions so you can re-use them
# multiple times in the current module (here the number of AZs for the current region)
locals {
nb_azs = "${length(data.aws_availability_zones.available.names)}"
}
# The "resource" keyword will create a new resource in our AWS account
resource "aws_subnet" "public_subnets" {
# The "count" parameter allows you to loop and create a resource a variable number of times
# We create one subnet in each AZ for our current region. Since we are in eu-west-2,
# this will effectively create 3 subnets, one in each of eu-west-2a, eu-west-2b, eu-west-2c.
count = "${local.nb_azs}"
vpc_id = "${aws_vpc.vpc.id}"
# Note the use of the Terraform helper function "cidrsubnet" which calculates non-overlapping
# CIDR blocks for each subnet
cidr_block = "${cidrsubnet(aws_vpc.vpc.cidr_block, 8, count.index)}"
# We loop over the array of AZs initialised before
availability_zone = "${data.aws_availability_zones.available.names[count.index]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment