Part 2 - Create the VPC.

By Ben Outram / 2018-06-15

All of the following configuration blocks should be added to the project.tf file that we created previously.

Create a VPC to launch our instances into:

resource "aws_vpc" "vpc" {
  cidr_block = "10.0.0.0/16"

  tags {
    Name = "terraform-example-vpc"
  }
}

Create an internet gateway to give our subnet access to the outside world:

resource "aws_internet_gateway" "gateway" {
  vpc_id = "${aws_vpc.vpc.id}"

  tags {
    Name = "terraform-example-internet-gateway"
  }
}

Grant the VPC internet access on its main route table:

resource "aws_route" "route" {
  route_table_id         = "${aws_vpc.vpc.main_route_table_id}"
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = "${aws_internet_gateway.gateway.id}"
}

Create subnets in each availability zone to launch our instances into, each with address blocks within the VPC:

resource "aws_subnet" "main" {
  count                   = "${length(data.aws_availability_zones.available.names)}"
  vpc_id                  = "${aws_vpc.vpc.id}"
  cidr_block              = "10.0.${count.index}.0/24"
  map_public_ip_on_launch = true
  availability_zone       = "${element(data.aws_availability_zones.available.names, count.index)}"

  tags {
    Name = "public-${element(data.aws_availability_zones.available.names, count.index)}"
  }
}

Create a security group in the VPC which our instances will belong to:

resource "aws_security_group" "default" {
  name        = "terraform_security_group"
  description = "Terraform example security group"
  vpc_id      = "${aws_vpc.vpc.id}"

  # Allow outbound internet access.
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags {
    Name = "terraform-example-security-group"
  }
}

Finally let's declare the Availability Zones data source which allows access to the list of AWS availibilty zones for the region declared by the provider. We will split this into a new file. Create datasource.tf and add the following configuration block:

data "aws_availability_zones" "available" {}

We can now try another plan:

$ terraform plan -var-file="user.tfvars"

Terraform will perform the following actions:

  + aws_internet_gateway.gateway
  + aws_route.route
  + aws_security_group.default
  + aws_subnet.main[0]
  + aws_subnet.main[1]
  + aws_subnet.main[2]
  + aws_vpc.vpc

Plan: 7 to add, 0 to change, 0 to destroy.

Review the plan. If it looks good it's time to apply our changes and move on!

$ terraform apply -var-file="user.tfvars"

Apply complete! Resources: 7 added, 0 changed, 0 destroyed.

You can find all the source code for this part of the lab here in GitHub.

More posts in this series.