Terraform, provided by HashiCorp, is a tool to define both cloud and on-premise resources (database, compute, storage, networking, etc.) in a human-readable configuration file. So it becomes really easy to version, reuse, and share the whole infrastructure.

Terraform manages the cloud resources through the APIs of the respective cloud platform, and the Terraform provider enables it to do so. HashiCorp and the Terraform community wrote thousands of such providers to manage different types of resources. The most popular ones are Amazon Web Services, Azure, Google Cloud Platform, Helm, Kubernetes, etc. All the providers can be found in the registry.

Untitled

HashiCorp provides a binary package of Terraform that can be installed using a package manager. For Windows, chocolatey is a good option. The following command from the command line does the trick -

choco install terraform

Make sure to set the path of the installed terraform in the user environment variables and restart your machine if necessary before validating terraform installation by the following command -

 terraform -help

For more information, go here.

Now, we are going to provision an NGINX server using Docker as a provider with Terraform.

NGINX is a web server that can also be used as a reverse proxy, load balancer, mail proxy, and HTTP cache.

Docker is an open-source platform that provides the ability to package and run an application in a container. The container is a loosely isolated and lightweight environment, which makes it easier for more than one container to run simultaneously on the host. A container also doesn’t have to rely on its host machine, as it has everything installed to run an application. We can develop, test, and distribute an application easily using these containers.

Docker follows a client-server architecture. The server is known as the docker demon(dockerd). The Docker client communicates with dockerd through the REST APIs, and dockerd does all the heavy lifting and manages all the Docker objects, i.e., images, containers, networks, etc. We can get all these Docker features by simply installing the Docker desktop software. For installing the Docker desktop on Windows, we need to install WSL2 (the Windows Subsystem for Linux 2) first.

To provision the server using docker, the basic configuration is written in a main.tf file like the following -

Untitled

The HashiCorp Terraform extension can be used with vscode for syntax highlighting. Now, to prepare the directory for terraform commands, we run terraform init.

Untitled

Now by terraform plan, we can see all the changes terraform is about to make to our infrastructure and save the plan to a file so that it can be used later. We can see from the following image that 2 objects are going to be added to our architecture - one is the docker image and the other one is the container built from the image.

Untitled

Then terraform apply builds the whole infrastructure.