# Understanding the Basics of Terraform

An open source infrastructure as code (IaC) software tool that **allows DevOps engineers to programmatically provision the physical resources an application requires to run**.

## What is Terraform?

Terraform is an open source and declarative tool for infrastructure provisioning. It let’s you manage your infrastructure and the platform and services that run on that infrastructure.

A good example of this would be, when you start your own project, say that you would need

* 3 servers
    
    * Private network space
        
    * Install Docker and other tools on each server
        
    * Security Setup | Firewalls
        
* 5 microservices as docker containers
    

Therefore, first you would need to provision your infrastructure by setting up a space to deploy you application. Terraform would be used to set up that space to deploy your microservices. These have to be created in a certain order since there might be task that is dependant on another.

## How does it work?

For terraform to work, it needs to connect with your IaaS provider such as AWS, GCP, Azure, Hetzner, Linode etc. For terraform to do this, it has two main components that make up its architecture:

* The Core
    
    * The core uses two inputs to do its job. Using these it figures out the plan to get things done.
        
        * **Terraform configuration**, where you as a user would write and define what needs to be created or provisioned.
            
        * **Terraform state**, is where it keeps the up to date state of how the current setup of your infrastructure looks like.
            
* The Provider
    
    * Terraform uses providers such as IaaS or PaaS providers. Terraform has hundreds of providers which give terraform access to their resources.
        

It is helpful to note that when writing terraform code, it uses a declarative approach, as opposed to an imperative one. When using a declarative approach, you tell terraform what the end result you would want to see is. Eg: I want 3 servers with the specified network config.

# Commands

---

Set TF\_LOG variable to check for Terraform logs during TF build or destroy.

```plaintext
TF_LOG=TRACE
```

Initialize Terraform to start working.

```plaintext
terraform init
```

Get list of terraform workspaces

```plaintext
terraform workspace list
```

Check if the changes you’ve made are working before applying/ destroying terraform.

```plaintext
terraform plan
```

Query’s the provider to get an up to date state.

```plaintext
terraform refresh
```

Creates new TF workspace

```plaintext
terraform workspace new <ws_name>
```

Select a TF workspace to work on.

```plaintext
terraform workspace select <ws_name>
```

Deletes an existing TF workspace.

```plaintext
terraform workspace delete <ws_name>
```

---
