Deploy and Manage an AWS VPC with Terraform
In this scenario, I am going to show you how to completely configure and deploy an AWS VPC with the aid of the powerful tool Terraform. Being Infrastructure as Code (IaC) this shows you just how easy it could be to replicate resources.
Feel free to follow along, I have uploaded all files to GitHub.
Here us the layout of the VPC we will be creating. It will host two EC2 instances, a webserver in a public subnet, and a Database in a private subnet.
The public subnet is accessable and all traffic is routed directly to the internet gateway we will be configuring.
The private subnet is completely cut off from the internet, all traffic in and out.
Verify your Terraform installation:
$ terraform --version
Variables let us set some default values that are easily repeatable. This is setting up our region, even the AMI used for our EC2 instances.
Now let’s set up our provider. This is rather straightforward, AWS is of course the provider and region refers to the variable previously defined.
This is where we lay out our entire VPC. We are setting up the public and private subnets. An Internet Gateway allows access to the internet. A route table contains a set of rules, called routes, that are used to determine where network traffic from your subnet or gateway is directed.
Multiple security groups are needed. The security group for our webserver allows our HTTP/HTTPS and SSH connections. Our Database security group enables MySQL port 3306, ping, and SSH from the public subnet.
We will need to set up some things for our EC2 instances. A key pair is needed to SSH to the instances that we are going to make. Then we define the AMI and configuration for the webserver, it is going to run a shell script which will install Apache Server for us. Lastly, we define our Database instance inside our private subnet.
This is the install script for Apache:
Now, it’s not good practices to keep your AWS keys in your Terraform files. We are going to set them as environment variables. Never store secrets in your Terraform files, especially if you intend to share them.
$ export AWS_ACCESS_KEY_ID="enter key without quotes"
$ export AWS_SECRET_ACCESS_KEY="enter key without quotes"
Now let’s run our Terraform code
$ terraform init
$ terraform validate
$ terraform plan
$ terraform apply
That’s it, now this can be replicated, built upon, whatever your heart desires. that is the magic of Terraform. We can now in a matter of minutes have this infrastructure completely built out.
$ terraform destroy
Don’t forget to destroy our creations to clean up. I hope you have enjoyed following along. If you want the code for this project, please check out GitHub. Thanks for reading.