Terraform - An Overview at High-Level
Tags: terraform, aws, beginners
Published: 2022-02-23 16:00:36

## What is Terraform? 🤔

Terraform is an open-source, cloud-agnostic, one of the most popular Infrastructure-as-code (IaC) tool developed by HashiCorp. It is used by DevOps teams to automate infrastructure tasks such as provisioning of your cloud resources.

Terraform supported immutable infrastructure, a declarative language, a masterless and agentless architecture, and had a large community and a mature codebase.

## Benefits of using Terraform:

* Does orchestration, not just configuration management
* Supports multiple providers such as AWS, Azure, Oracle, GCP, and many more
* Provide immutable infrastructure where configuration changes smoothly
* Uses easy to understand language, HCL (HashiCorp configuration language)
* Easily portable to any other provider

## How Terraform Works?

Terraform has two main components that make up its architecture:

* Terraform Core
* Terraform Providers

## Terraform Configuration Files

Configuration files are a set of files used to describe infrastructure in Terraform and have the file extensions .tf and .tf.json. Terraform uses a declarative model for defining infrastructure. Configuration files let you write a configuration that declares your desired state. Configuration files are made up of resources with settings and values representing the desired state of your infrastructure.

![terraform-config-files-e1605834689106](https://user-images.githubusercontent.com/83613651/153713600-6cd87f78-0d94-4e1b-9951-7d28009a1b7b.png)

A Terraform configuration is made up of one or more files in a directory, provider binaries, plan files, and state files once Terraform has run the configuration.

1. **Configuration file** (*.tf files): Here we declare the provider and resources to be deployed along with the type of resource and all resources specific settings

2. **Variable declaration file** (variables.tf or variables.tf.json): Here we declare the input variables required to provision resources

3. **Variable definition files** (terraform.tfvars): Here we assign values to the input variables

4. **State file** (terraform.tfstate): a state file is created once after Terraform is run. It stores state about our managed infrastructure.

## Terraform Providers
A provider is responsible for understanding API interactions and exposing resources. It is an executable plug-in that contains code necessary to interact with the API of the service. Terraform configurations must declare which providers they require so that Terraform can install and use them.

![Terraform-provider-api-call](https://user-images.githubusercontent.com/83613651/153762048-55367d88-76ae-4d32-90da-c5171f91d73b.png)

Terraform has over a hundred providers for different technologies, and each provider then gives terraform user access to its resources. So through AWS provider, for example, you have access to hundreds of AWS resources like EC2 instances, the AWS users, etc.

## Terraform Core Concepts

1. **Variables**: Terraform has input and output variables, it is a key-value pair. Input variables are used as parameters to input values at run time to customize our deployments. Output variables are return values of a terraform module that can be used by other configurations.

2. **Provider**: Terraform users provision their infrastructure on the major cloud providers such as AWS, Azure, OCI, and others. A provider is a plugin that interacts with the various APIs required to create, update, and delete various resources.

3. **Module**: Any set of Terraform configuration files in a folder is a module. Every Terraform configuration has at least one module, known as its root module.

4. **State**: Terraform records information about what infrastructure is created in a Terraform state file. With the state file, Terraform is able to find the resources it created previously, supposed to manage and update them accordingly.

5. **Resources**: Cloud Providers provides various services in their offerings, they are referenced as Resources in Terraform. Terraform resources can be anything from compute instances, virtual networks to higher-level components such as DNS records. Each resource has its own attributes to define that resource.

6. **Data Source**: Data source performs a read-only operation. It allows data to be fetched or computed from resources/entities that are not defined or managed by Terraform or the current Terraform configuration.

7. **Plan**: It is one of the stages in the Terraform lifecycle where it determines what needs to be created, updated, or destroyed to move from the real/current state of the infrastructure to the desired state.

8. **Apply**: It is one of the stages in the Terraform lifecycle where it applies the changes real/current state of the infrastructure in order to achieve the desired state.

### Terraform Lifecycle
Terraform lifecycle consists of – init, plan, apply, and destroy.

![terraform-lifecycle](https://user-images.githubusercontent.com/83613651/153762027-3da8e99b-2166-4ddf-b0b6-4614e97db1f3.png)

## Terraform-lifecycle

1. Terraform init initializes the (local) Terraform environment. Usually executed only once per session.
2. Terraform plan compares the Terraform state with the as-is state in the cloud, build and display an execution plan. This does not change the deployment (read-only).
3. Terraform apply executes the plan. This potentially changes the deployment.
4. Terraform destroy deletes all resources that are governed by this specific terraform environment.

## Hands-on : Create a EC2 instance using Terraform
 
**Prerequisite**: A laptop or machine with terraform installed and AWS cli configured

* **Step 1**: Create main.tf and variables.tf inside a folder

main.tf
```
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

resource "aws_instance" "app_server"{
  ami           = var.ami
  instance_type = var.instance_type
  tags = {
    Name = "TerraInstance"
  }
}
```

variables.tf
```
variable "ami" {
    type = string
    default = "ami-0c6615d1e95c98aca"
}
variable "instance_type" {
    type = string
    default = "t2.micro"
}
```
* **Step 2** : Initialize the directory with *$ terraform init* command

* **Step 3** : Run *$ terraform plan* command to print out the execution plan

* **Step 4** : Apply the configuration now with the *$ terraform apply* command.
* **Step 5** : Inspect the current state using *$ terraform show* and check AWS console whether a instance is created.
* **Step 6** : Run *$ terraform destroy* command to destroy the created instance.

Thats it!!! Now that you sucessfully created a EC2 instance with terraform.

Checkout my github repository for more 💁:
https://github.com/iamvinot/terraform-project