Learn Terraform Basics - Day 1

Learn Terraform Basics - Day 1

What is Terraform?

Terraform is a tool that helps you manage and create infrastructure (like servers, databases, and networks) using code.

Terraform is an open-source tool developed by HashiCorp that enables you to define and manage your infrastructure using code.

It follows the concept of Infrastructure as Code (IaC), allowing you to describe your infrastructure in configuration files. This approach simplifies automation, version control, and replication of your infrastructure.

I would like to explain the same content in very simple and easy manner, then anyone can easily understand the concept of the Terraform.

Example Imagine you're building a house. You need to create a plan (or blueprint) that describes what the house should look like, what materials to use, and how to build it.

Terraform works in a similar way. You write code (in a human-readable format) that describes what your infrastructure should look like and Terraform takes care of creating and managing it for you. This is called Declarative syntax, just will define what we want to terraform will take the remaining all things.

Note: here will get some doubt : what is IAC ? Let’s start discus about the IAC in simple words.

What is Infrastructure as Code (IaC)?

Think of IaC as writing a recipe for your infrastructure. Instead of clicking buttons or typing commands manually, you write instructions in a configuration file that tells your computer or cloud provider exactly how to set things up.

Currently, there are about 10-15 IaC tools available in the market, but here I am listing the top 5 IaC tools.

  1. Terraform
  • Provided by: HashiCorp

  • Description: Terraform is an open-source IAC tool that supports multiple cloud providers like AWS, GCP, and Azure Cloud.

  • Key Features: Multi-cloud support, modular configuration, state management

  1. AWS CloudFormation
  • Provided by: Amazon Web Services (AWS)

  • Description: AWS CloudFormation is a tool provided by AWS that allows you to manage infrastructure and automate deployments using code.

  • Key Features: Supports AWS resources, integrates with AWS services, version control

  1. Pulumi
  • Provided by: Pulumi Corporation

  • Description: Pulumi is an IAC tool that supports multiple programming languages like Python, JavaScript, C#, Go, and TypeScript.

  • Key Features: Multi-language support, modular configuration, integration with CI/CD tools

  1. Ansible
  • Provided by: Red Hat

  • Description: Ansible is an orchestration and configuration tool that uses Playbooks written in YAML.

  • Key Features: Agentless architecture, modular configuration, integration with CI/CD tools

  1. Azure Resource Manager (ARM)
  • Provided by: Microsoft

  • Description: Azure Resource Manager is a tool provided by Microsoft that uses ARM templates to handle dependencies and infrastructure.

  • Key Features: Supports Azure resources, integrates with Azure services, version control

In the list above, I have chosen Terraform as the IaC tool and will continue this blog with it.

Why Use Terraform?

Terraform is a powerful Infrastructure as Code (IaC) tool that automates the provisioning and management of infrastructure. Here's why it's a great choice:

  1. Multi-Cloud Support:

    • Terraform works seamlessly across multiple cloud providers like AWS, Azure, Google Cloud, and more.

    • You can manage resources from different providers in a single configuration file.

  2. Consistency:

    • Terraform ensures your infrastructure setup is consistent every time you apply the code, eliminating manual errors.
  3. Automation:

    • Automate infrastructure creation, updates, and destruction.

    • Save time and reduce the need for repetitive manual tasks.

  4. Collaboration:

    • Configuration files can be shared and version-controlled using tools like Git.

    • Teams can collaborate effectively while maintaining clear visibility into infrastructure changes.

  5. Cost Efficiency:

    • Helps optimize resource usage by easily scaling up or down.

    • Quickly remove unused infrastructure to avoid unnecessary costs.

Key Benefits of Using Terraform

  1. Declarative Configuration:

    • You describe what you want your infrastructure to look like and Terraform figures out how to achieve it.

    • Example:

        hcl
        resource "aws_instance" "example" {
          ami           = "ami-0c55b159cbfafe1f0"
          instance_type = "t2.micro"
        }
      
  2. Infrastructure as Code (IaC):

    • Define your entire infrastructure in reusable and shareable configuration files.

    • Easily track changes and maintain version control.

  3. Idempotency:

    • Running the same configuration multiple times yields the same result, ensuring predictable outcomes.
  4. Extensive Ecosystem:

    • Terraform has a vast library of providers and modules, enabling you to manage nearly any resource.

    • Whether it's VMs, databases, or networking, Terraform supports it all.

  5. State Management:

    • Terraform maintains a state file to track the current state of your infrastructure.

    • This helps it understand the difference between the existing setup and the desired setup.

  6. Plan Before Execution:

    • The terraform plan command previews changes before applying them, reducing the risk of errors.

    • Example:

        terraform plan
      
  7. Reusability:

    • Create reusable modules for common setups, like VPCs or load balancers, saving time in future projects.
  8. Scalability:

    • Scale infrastructure up or down easily by modifying the code.

    • Terraform is designed to handle small setups as well as large-scale deployments.

When Should You Use Terraform?

  • Managing Multi-Cloud Environments: If you're using resources from multiple cloud providers.

  • Automating Repeated Tasks: To set up development, staging, and production environments with consistency.

  • Large and Complex Infrastructure: To handle numerous resources with dependencies.

  • Version Control for Infrastructure: If you want to track and roll back changes like code.

Terraform Life Cycle

Terraform follows a simple life cycle to manage infrastructure efficiently. It consists of six key steps: Write, Initialize, Plan, Apply, Manage, and Destroy. Let’s break it down with a practical example.

Here’s a diagram illustrating the Terraform Life Cycle with six steps: Write Configuration, Initialize, Plan, Apply, Manage Changes, and Destroy. It visually represents the iterative process of using Terraform.

Let's look at the table below, which explains this in a simple way.

Summary Table

StepCommandPurpose
WriteN/ADefine your infrastructure in .tf files.
Initializeterraform initSet up the environment and download provider plugins.
Planterraform planPreview changes before applying them.
Applyterraform applyCreate or update the infrastructure.
ManageEdit and applyMake incremental changes to the infrastructure.
Destroyterraform destroyRemove all resources defined in the configuration.

Let’s discuss all the steps in detailed manner.

1. Write

  • You start by writing configuration files in Terraform's HashiCorp Configuration Language (HCL). These files describe the infrastructure you want to create, such as servers, databases, and networks.

Example:

hcl
provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

This code tells Terraform to create an AWS EC2 instance in the us-west-2 region using the specified AMI and instance type.


2. Initialize

  • Run terraform init to initialize your working directory.

  • This step downloads necessary provider plugins (like AWS, Azure) and sets up the environment.

Example:

terraform init

Result: Terraform downloads the AWS provider and prepares to execute the configurations.


3. Plan

  • Run terraform plan to preview the changes Terraform will make to your infrastructure.

  • It shows what resources will be created, updated, or destroyed without actually making any changes.

Example:

terraform plan

Result: You see a summary of the actions Terraform will take, such as creating an EC2 instance.


4. Apply

  • Run terraform apply to execute the plan and create the specified resources.

  • Terraform interacts with your provider (e.g., AWS) to set up the infrastructure as defined in your configuration files.

Example:

terraform apply

Result: Terraform provisions the EC2 instance. It also updates a state file (terraform.tfstate) to track the current state of the infrastructure.


5. Manage

  • Once the infrastructure is created, you can update or modify it by editing the configuration files and reapplying them.

  • Terraform calculates the difference between the desired state (your updated configuration) and the current state (tracked in the state file) and makes only the necessary changes.

Example:

If you update the instance type in the configuration:

hcl
instance_type = "t2.small"

Run terraform apply again, and Terraform will update the instance type without affecting other resources.


6. Destroy

  • Use terraform destroy to remove all the resources defined in your configuration.

  • This is useful when you no longer need the infrastructure or are cleaning up after testing.

Example:

terraform destroy

Result: Terraform deletes the EC2 instance and other resources it created.

Note: terraform plan helps you catch potential mistakes in your configuration before they affect your infrastructure.