Classless Inter-Domain Routing (CIDR) block is a notation that allows you to specify a range of IPv4 addresses for the VPC. Visit cidr.xyz to check how many IP addresses you will have available for a certain CIDR block.
The first four IP addresses and the last IP address in each subnet CIDR block are reserved, not available for use. In a subnet with CIDR block 10.0.1.0/24 the following IP addresses are reserved:
10.0.1.0/24 - Network address
10.0.1.1/24 - Reserved by AWS for the VPC router
10.0.1.2/24 - Reserved by AWS for IP address of DNS server
10.0.1.3/24 - Reserved by AWS for future use
10.0.1.255/24 - Network broadcast address
Let's create a network for our infrastructure. In terraform directory , create network directory with main.tf file.
Apply changes and check subnet associations for the Main Route Table.
Subnets that are not explicitly associated with any route table are associated with the main route table. Never associate Internet Gateway with the Main Route Table to not expose your private resources by accident!
Let's explicitly make two subnets public. To do that we need to create a new Route Table and an Internet Gateway associated with it, and then associate subnets with the table.
For now, the VPC configuration is ready. We need to test if it works correctly. For this purpose in terraform directory create webserver-cluster directory with main.tf file. At this point we will create a configuration required to test the VPC, later it will be transformed into a webserver cluster configuration.
output "public_ip_address" {
value = aws_instance.public.public_ip
}
output "private_ip_address" {
value = aws_instance.private.private_ip
}
Apply changes in network and then webserver-cluster directory.
To be able to connect via ssh from the EC2 instance in the public subnet to the EC2 instance in the private subnet copy your private key to EC2 instances using scp.
Connect via ssh with the EC2 instance in the public subnet and execute the following command to check whether it has a route to the Internet.
$ sudo apt-get update
Next, connect to the EC2 instance in the private subnet and perform the same test.
To connect securely to EC2 instances in private subnets use Bastion Hosts. Do not use the presented way. It's not secure. We did this only for quick testing, resources will be destroyed soon.