Creating Demilitarized Zone in AWS for better security using Terraform

Dipaditya Das
13 min readJul 18, 2020

Lets say you want to deploy a Web-app(like WordPress) with a Database(MySQL) but you don’t know to secure them in the best ways.

Well, in this article I am going to cover something called “Demilitarized Zone”, and how it actually makes a better security for the IT industry. But before that we need to clear some basics.

What is AWS?

AWS stands for Amazon Web Services. It is a public cloud. It is the world’s most comprehensive and broadly adopted cloud platform, offering over 175 fully featured services from data centers globally. It is a subsidiary of Amazon that provides on-demand cloud computing platforms and APIs to individuals, companies, and governments, on a metered pay-as-you-go basis. There are 24 globally launched Regions with 76 Availability Zones and 216 Points of Presence (205 Edge Locations and 11 Regional Edge Caches).

What is VPC?

A virtual private cloud (VPC) is an on-demand configurable pool of shared computing resources allocated within a public cloud environment, providing a certain level of isolation between the different organizations (denoted as users hereafter) using the resources. The isolation between one VPC user and all other users of the same cloud (other VPC users as well as other public cloud users) is achieved normally through allocation of a private IP subnet and a virtual communication construct (such as a VLAN or a set of encrypted communication channels) per user. In a VPC, the previously described mechanism, providing isolation within the cloud, is accompanied with a VPN function (again, allocated per VPC user) that secures, by means of authentication and encryption, the remote access of the organization to its VPC resources. With the introduction of the described isolation levels, an organization using this service is in effect working on a ‘virtually private’ cloud (that is, as if the cloud infrastructure is not shared with other users), and hence the name VPC.

What is AWS VPC?

Amazon Virtual Private Cloud (Amazon VPC) lets you provision a logically isolated section of the AWS Cloud where you can launch AWS resources in a virtual network that you define. You have complete control over your virtual networking environment, including selection of your own IP address range, creation of subnets, and configuration of route tables and network gateways. You can use both IPv4 and IPv6 in your VPC for secure and easy access to resources and applications. You can easily customize the network configuration of your Amazon VPC. For example, you can create a public-facing subnet for your web servers that have access to the internet. You can also place your backend systems, such as databases or application servers, in a private-facing subnet with no internet access. You can use multiple layers of security, including security groups and network access control lists, to help control access to Amazon EC2 instances in each subnet.

What is Subnets?

A subnet, or subnetwork, is a network inside a network. Subnets make networks more efficient. Through subnetting, network traffic can travel a shorter distance without passing through unnecessary routers to reach its destination.

A VPC spans all of the Availability Zones in the Region. After creating a VPC, you can add one or more subnets in each Availability Zone. You can optionally add subnets in a Local Zone, which is an AWS infrastructure deployment that places compute, storage, database, and other select services closer to your end users. A Local Zone enables your end users to run applications that require single-digit millisecond latencies. For information about the Regions that support Local Zones, see Available Regions in the Amazon EC2 User Guide for Linux Instances. When you create a subnet, you specify the CIDR block for the subnet, which is a subset of the VPC CIDR block. Each subnet must reside entirely within one Availability Zone and cannot span zones. Availability Zones are distinct locations that are engineered to be isolated from failures in other Availability Zones. By launching instances in separate Availability Zones, you can protect your applications from the failure of a single location. We assign a unique ID to each subnet. You can also optionally assign an IPv6 CIDR block to your VPC, and assign IPv6 CIDR blocks to your subnets.

What is Internet Gateway?

An internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows communication between your VPC and the internet. An internet gateway serves two purposes: to provide a target in your VPC route tables for internet-routable traffic, and to perform network address translation (NAT) for instances that have been assigned public IPv4 addresses. An internet gateway supports IPv4 and IPv6 traffic. It does not cause availability risks or bandwidth constraints on your network traffic.

What is Route Table?

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. Your VPC has an implicit router, and you use route tables to control where network traffic is directed. Each subnet in your VPC must be associated with a route table(Route Table Association), which controls the routing for the subnet (subnet route table). You can explicitly associate a subnet with a particular route table. Otherwise, the subnet is implicitly associated with the main route table. A subnet can only be associated with one route table at a time, but you can associate multiple subnets with the same subnet route table.

What is Demilitarized Zone?

In computer security, a DMZ or demilitarized zone (sometimes referred to as a perimeter network or screened subnet) is a physical or logical subnetwork that contains and exposes an organization’s external-facing services to an untrusted, usually larger, network such as the Internet. The purpose of a DMZ is to add an additional layer of security to an organization’s local area network (LAN): an external network node can access only what is exposed in the DMZ, while the rest of the organization’s network is firewalled. The DMZ functions as a small, isolated network positioned between the Internet and the private network and, if its design is effective, allows the organization extra time to detect and address breaches before they would further penetrate into the internal networks.

A public subnet is directly routable to the Internet via a route in the route table that points to the Internet gateway. This type of subnet allows the use of Elastic IPs and public IPs, and (if the security group and network ACLs permit) a public subnet is reachable from the Internet. A public subnet is useful as a DMZ infrastructure for web servers and for Internet-facing Elastic Load Balancing (ELB) load balancers.

Private subnets can indirectly route to the Internet via a NAT instance or NAT gateway. These NAT devices reside in a public subnet in order to route directly to the Internet. Instances in a private subnet are not externally reachable from outside the Amazon VPC, regardless of whether they have a public or Elastic IP address attached. A private subnet is useful for application servers and databases.

What is Terraform?

Terraform is the infrastructure as a code offering from HashiCorp. It is a tool for building, changing and managing infrastructure in a safe, repeatable way. Operators and Infrastructure teams can use Terraform to manage environments with a configuration language called the HashiCorp Configuration Language (HCL) for human-readable, automated deployments.

Terraform works with over 160 different providers for a broad set of common infrastructure. Provider SDK makes it simple to create new and custom providers. Providers leverage infrastructure-specific APIs to preserve unique capabilities for each provider.

Prerequisite for the Practical

  1. AWS IAM user with power user policy
  2. AWS CLI and profile of IAM user created
  3. Terraform
  4. Visual Studio Code with Terraform extension

Let’s Get Started with Terraform Automation

In this practical we will perform the following tasks:

  1. Write a Infrastructure as code using terraform, which automatically create a VPC.
  2. In that VPC we have to create 2 subnets: (a) public subnet [ Accessible for Public World! ](b) private subnet [ Restricted for Public World! ]
  3. Create a public facing internet gateway for connect our VPC/Network to the internet world and attach this gateway to our VPC.
  4. Create a routing table for Internet gateway so that instance can connect to outside world, update and associate it with public subnet.
  5. Launch an ec2 instance which has WordPress setup already having the security group allowing port 80 so that our client can connect to our WordPress site.
  6. Also attach the key to instance for further login into it.
  7. Launch an ec2 instance which has MYSQL setup already with security group allowing port 3306 in private subnet so that our WordPress VM can connect with the same.
  8. Also attach the key with the same.

Note: WordPress instance has to be part of public subnet so that our client can connect our site. MySQL instance has to be part of private subnet so that outside world can’t connect to it. Don’t forgot to add auto IP assign and auto DNS name assignment option to be enabled.

Step-1: Configure AWS CLI

AWS CLI in PowerShell 7(Win10)

Step-2: Create a terraform file (main.tf)

I am creating an main.tf file and coding our cloud provider, i.e., AWS. We are also providing the availability zone (Mumbai) with my AWS CLI profile name.

main.tf

Step-3: Creating VPC(Virtual Private Cloud)

Amazon Virtual Private Cloud (Amazon VPC) enables us to launch AWS resources into a virtual network that we have defined. This virtual network closely resembles a traditional network that we would operate in our own data center, with the benefits of using the scalable infrastructure of AWS. Its basically the network layering of EC2 instances. Here I have created an AWS VPC in the same availability zone (Mumbai).

aws_vpc.tf

Step-4: Creating Internet gateway

An internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows communication between our VPC and the internet. An internet gateway serves two purposes: to provide a target in our VPC route tables for internet-routable traffic, and to perform network address translation (NAT) for instances that have been assigned public IPv4 addresses. An internet gateway supports IPv4 and IPv6 traffic. It does not cause availability risks or bandwidth constraints on our network traffic. I have created an Internet gateway for my AWS VPC.

aws_igw.tf

Step-5: Create a Routing Table

A route table contains a set of rules, called routes, that are used to determine where network traffic from our subnet or gateway is directed. This route table is for inbound traffic to VPC through internet gateway.

aws_route_table.tf

Step-6: Create two Subnets in VPC

Here we will created Public subnet for Web-App(WordPress) and a Private subnet for Database(MySQL).

aws_publicsubnet.tf
aws_privatesubnet.tf

Step-7: Creating an association between route table and subnet

Each subnet in your VPC must be associated with a route table. A subnet can be explicitly associated with custom route table, or implicitly or explicitly associated with the main route table.

aws_rt_assoc.tf

Step-8: Creating two Security Group

A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. When we launch an instance in a VPC, we can assign up to five security groups to the instance. Security groups act at the instance level, not the subnet level. Therefore, each instance in a subnet in our VPC can be assigned to a different set of security groups. We will create two security groups, one for WordPress EC2 instance and the other for Database EC2 instance.

aws_WebSG.tf
aws_DatabaseSG.tf

Step-9: Create a Key-Pair

Here we have created a key-pair using Terraform tls_private_key generates a secure private key and encodes it as PEM. This resource is primarily intended for easily bootstrapping throwaway development environments. This is a logical resource, so it contributes only to the current Terraform state and does not create any external managed resources.

aws_keypair.tf

Step-10: Create an EC2 Instance for WordPress

Here we have used the WordPress Images from Aurora.

aws_Wordpress_ec2.tf

Step-11: Create an EC2 Instance for MySQL

Here we have used the Amazon Linux 2 AMI for MySQL.

Step-12 : Show the Output in Browser

Here we will launch Edge browser after the completion of all the above steps.

output.tf

Step-13 : Initiate the working directory with Terraform Command

The terraform initcommand is used to initialize a working directory containing Terraform configuration files. This is the first command that should be run after writing a new Terraform configuration or cloning an existing one from version control. It is safe to run this command multiple times.

Step-14: Validate the terraform files

The terraform validate command validates the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc. Validate runs checks that verify whether a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state. It is thus primarily useful for general verification of reusable modules, including correctness of attribute names and value types. It is safe to run this command automatically, for example as a post-save check in a text editor or as a test step for a re-usable module in a CI system.

Step-15: Create an execution plan

The terraform plan command is used to create an execution plan. Terraform performs a refresh, unless explicitly disabled, and then determines what actions are necessary to achieve the desired state specified in the configuration files. This command is a convenient way to check whether the execution plan for a set of changes matches your expectations without making any changes to real resources or to the state. For example, terraform plan might be run before committing a change to version control, to create confidence that it will behave as expected.

After the successful execution we will see that our vpc, internet gateway, subnets, route table, route table association, security groups and EC2 instances .

Then we will see something like this 👇

Now we have to enter the WordPress Instance ID to continue to out next page.

Now we have to enter the our WordPress password and hit submit.

Then we have to login the WordPress site using Username: aurora with our new password that we provided.

Then we will create our first article.

Step-16: Destroy the Entire Infrastructure

The terraform destroy command is used to destroy the Terraform-managed infrastructure. The --auto-approve option helps us to skip the approval part where terraform program prompts us whether to continue or cancel the process.

terraform destroy --auto-approve

GitHub Repository

Connect me on Linkedin

--

--

Dipaditya Das

IN ● MLOps Engineer ● Linux Administrator ● DevOps and Cloud Architect ● Kubernetes Administrator ● AWS Community Builder ● Google Cloud Facilitator ● Author