Terraform part-1

Introduction

What is terraform?

In today’s fast-paced DevOps landscape, automation is a necessity. Manual infrastructure management is time-consuming, error-prone, and lacks scalability. This is where Terraform, an Infrastructure as Code (IaC) tool, comes into play. Terraform simplifies the provisioning, management, and scaling of cloud and on-premise infrastructure using a declarative approach.

Terraform is an open-source IaC tool developed by HashiCorp that enables DevOps teams to define and manage infrastructure using configuration files. It allows users to create, modify, and destroy infrastructure efficiently by interacting with various cloud providers like AWS, Azure, Google Cloud, and even on-premise solution. It uses a declarative language to define the desired end state while determining execution steps and supports an imperative style for explicitly defining execution processes.

Why Terraform?

With the increasing complexity of cloud-native applications, organizations require automation for managing infrastructure. Terraform provides:

  • Infrastructure as Code: Define infrastructure in human-readable configuration files.
  • Multi-Cloud Support: Manage AWS, Azure, GCP, and on-premise infrastructure with a single tool.
  • Declarative Syntax: Instead of writing step-by-step instructions (imperative), define the desired state, and Terraform will figure out how to achieve it.
  • Version Control: Terraform configurations can be stored in Git, enabling tracking of changes.
  • Scalability & Consistency: Ensure uniform deployment across different environments (development, staging, production).
  • Infrastructure Automation – Automates setup of VPC, servers, security, and Docker installation.
  • Order Execution – Ensures tasks run in the correct sequence.
  • Scalability & Configuration Management – Easily add servers, update security, and modify configurations.
  • Simplified Maintenance – Streamlines ongoing infrastructure management.
  • Replication & Environment Setup – Enables quick replication of infrastructure for production, development, and staging environments.

 

Difference Between Terraform and Ansible

Terraform and Ansible are both Infrastructure as Code (IaC) tools used for automating infrastructure management, but they serve different primary purposes.

  • Terraform is primarily an infrastructure provisioning tool, excelling in creating and managing infrastructure components like servers, networks, and security configurations. It is relatively new, dynamically evolving, and more advanced in orchestration.
  • Ansible is mainly a configuration management tool, used after infrastructure provisioning to configure servers, deploy applications, and install or update software. It is more mature and widely adopted for post-provisioning tasks.

Terraform Architecture

Terraform connects to infrastructure providers like AWS to provision and manage resources using two main components:

  1. Terraform Core
    • Uses two input sources:
      • Terraform Configuration – User-defined infrastructure setup.
      • Terraform State – Stores the current state of the infrastructure.
    • Compares the current state with the desired configuration and determines:
      • What needs to be created, updated, or deleted.
      • The execution order to achieve the desired state.

 

  1. Terraform Providers
    • Enable Terraform to interact with various platforms:
      • Cloud Providers – AWS, Azure, GCP for infrastructure management.
      • Platform as a Service (PaaS) – Kubernetes, databases, and managed services.
      • Software as a Service (SaaS) – Other cloud-based tools.
    • Providers grant Terraform access to platform-specific resources, e.g., AWS provider allows managing EC2 instances, IAM users, while Kubernetes provider manages deployments, services, and namespaces.

Execution Process:

  • Terraform Core compares the configuration with the current state and generates an execution plan.
  • Terraform uses providers to execute the plan by connecting to the relevant platforms.
  • Ensures end-to-end infrastructure provisioning, from networking and servers to application deployments.

Configuration File

Terraform uses an intuitive syntax where users define the desired resource, specify the provider, and set its attributes. Terraform then provisions and manages the resource accordingly.

Example1: AWS provider is configured and through the provider we now have to AWS resource like VPC, and we can create that with some attributes.

terraform {

required_providers {

aws = {

source  = “hashicorp/aws”

version = “~> 5.0”

}

}

}

# Configure the AWS Provider

provider “aws” {

region = “us-east-1”

}

# Create a VPC

resource “aws_vpc” “example” {

cidr_block = “10.0.0.0/16”

tags = {

Name = “example-vpc”

}

}

Example2: The same way we have the Kubernetes provider configured and through that now we can create a Kubernetes namespace resource where we pass some attributes.

terraform {

required_providers {

kubernetes = {

source  = “hashicorp/kubernetes”

version = “~> 2.0”

}

}

}

# Configure the Kubernetes Provider

provider “kubernetes” {

config_context_auth_info = “ops”

config_context_cluster   = “mycluster”

}

# Create a Kubernetes Namespace

resource “kubernetes_namespace” “example” {

metadata {

name = “my-first-namespace”

}

}

Declarative vs Imperative:

In a declarative approach, Terraform users define the desired end state rather than specifying step-by-step instructions. For example, instead of detailing how to create a VPC or spin up EC2 instances, users declare “I want 5 servers with this network configuration and an AWS user with specific permissions.” Terraform then figures out how to achieve that state.

In contrast, an imperative approach requires explicitly defining each step, such as “Remove 2 servers, add a firewall configuration, and update user permissions.”

While both approaches may look similar initially, declarative configuration simplifies updates and maintenance. Users adjust the desired state and Terraform determines the necessary changes automatically. This keeps configuration files clean and manageable, while also ensuring that the current setup reflects the final declared state.

Terraform commands for different stages

  1. Refresh
    • terraform refresh , Queries the infrastructure provider (e.g., AWS) to get the current state of the infrastructure.
  2. Plan
    • terraform plan
    • Compares the current state with the desired state in the configuration file and determines the required changes.
    • If it’s an initial setup, it defines all the steps to create the infrastructure.
    • If it’s an update, it calculates the necessary adjustments (e.g., adding a server, modifying permissions).
  3. Apply
    • terraform apply
    • Executes the plan and applies the necessary changes to reach the desired state.
    • Terraform automatically performs refresh before applying the plan.
  4. Destroy
    • terraform destroy
    • Deletes all created infrastructure resources in the correct order, reverting everything to its initial state.
    • Useful for temporary setups like demo environments.

Each command follows a structured workflow, ensuring efficient provisioning, updating, and cleanup of infrastructure.

Command

Description

terraform init

Initializes Terraform in the working directory.

terraform plan

Shows what changes Terraform will make.

terraform apply

Deploys the infrastructure as per the configuration file.

terraform destroy

Removes all resources defined in the configuration.

Terraform is a universal Infrastructure as Code (IaC) tool that supports multi-cloud and hybrid environments, enabling a single tool to manage on-premise and cloud infrastructure. Instead of separate teams handling AWS, Google Cloud, or on-premise servers, Terraform allows centralized infrastructure management. It integrates with various technologies and platforms like AWS, Kubernetes, Jenkins, and VMware, providing a unified interface to interact with their APIs, eliminating the need to learn each platform’s specific API.