DEV Community

Anand Ghangoria
Anand Ghangoria

Posted on

Terraform Made Easy: A Hands-On Introduction for Beginners

This article provides a professional introduction to Terraform, outlining its core features, workflow, and significance in modern DevOps practices. We’ll explore common use cases relevant to various environments and highlight initial challenges to help streamline your adoption of Terraform. Let’s get started.

History of Terraform

The inventor of terraform is Mitchell Hashimoto, the co-founder of Hashicrop.

It was designed as an infrastructure as code (IaC) tool to help automate cloud infrastructure provisioning.
2014: Initial release by Hashicrop.
2017: Introduction of HCL(Hashicrop Configuration Language)
2021: Terraform 1.0 released, as stable for production use.
2023: Opensource ---> Bussiness Source License (BSL).

What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) is a method of managing and setting up IT infrastructure using code, instead of manually configuring hardware or using point-and-click tools. With IaC, you write configuration files that tell the system what resources to create, making the process faster, repeatable, and more reliable.

Image description

The image above illustrates how traditional infrastructure operates.

Why Terraform?

Terraform helps organizations reduce manual work, improve efficiency, and maintain infra-structure consistency across different environment.

What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows you to define, provision, and manage cloud infrastructure using simple, human-readable configuration files written in HashiCorp Configuration Language (HCL).

Seamlessly integrating with CI/CD pipelines, Terraform automates infrastructure provisioning and changes, streamlining development workflows and ensuring repeatability across environments.

Key Terraform components

Terraform is stateful, tracking the state of the infrastructure by comparing the current defined IaC configuration and a state file it generates after a Terraform run. This introduces a layer of complexity because you need to manage this state file.

Providers

  • Define which platform or service you're interacting with (e.g., AWS, Azure, GCP, Kubernetes).

Example:

provider "aws" { region = "us-east-1" }
Enter fullscreen mode Exit fullscreen mode

Resources

  • Represent the infrastructure objects you want to create or manage (e.g., EC2 instances, S3 buckets).

Example:

resource "aws_instance" "web" { ... }
Enter fullscreen mode Exit fullscreen mode

Modules

  • Group multiple resources together for reuse and organization.

  • Help you follow DRY (Don't Repeat Yourself) principles.

  • Example: A reusable VPC module used across environments.

Variables

Allow you to customize configurations without changing the code.

Example:

variable "instance_type" { default = "t2.micro" }
Enter fullscreen mode Exit fullscreen mode

Outputs

Show useful information after a Terraform run (e.g., IP address of a created instance).

Example:

output "instance_ip" { value = aws_instance.web.public_ip }
Enter fullscreen mode Exit fullscreen mode

State

  • Tracks the current state of your infrastructure.

  • State stored in a .tfstate file, either locally or remotely (e.g., in S3).

Terraform Workflow

Terraform follows a simple yet powerful workflow to manage infrastructure as code:

  1. Init – Run terraform init to initialize the working directory and download providers.
  2. Plan – Preview changes with terraform plan before making any updates.
  3. Apply – Execute changes with terraform apply to provision or update resources.
  4. Destroy – Use terraform destroy, to Destroys all resources defined in your Terraform configuration.

🔍 File Overview

  • main.tf – The heart of your infrastructure.
  • variables.tf – Defines inputs for flexibility.
  • terraform.tfvars – Assigns real values to your variables.
  • outputs.tf – Makes key info accessible after deployment.
  • provider.tf – Sets up your cloud provider (e.g., AWS).
  • backend.tf – Configures remote state storage (optional but recommended).
  • versions.tf – Locks Terraform & provider versions.
  • modules/ – Reusable infrastructure components.
  • env/ – Isolated configurations for environments like dev/staging/prod.

📦 Pro Tip: Keep sensitive values (like secrets) out of version control. Use terraform.tfvars locally or manage secrets with tools like Vault or SSM.

Hashicrop Configuration Language (HCL)

What is HCL?

HCL (HashiCorp Configuration Language) is a declarative language designed by HashiCorp.

It is mainly used in tools like Terraform to define Infrastructure as Code (IaC).

  • Human-readable: Easy for people to write and understand.
  • Declarative: You describe what you want, not how to do it.
  • Optimized for machines: Easy for software to parse and process.

HCL allows you to manage and provision cloud resources (like AWS, Azure, GCP) in a clear and structured way.

HCL Syntax: Blocks, Parameters, and Arguments

1. Blocks

Blocks are the fundamental building units in HCL. They group configuration settings together.

  • A block starts with a block type (like resource, provider, variable).
  • It can have one or more labels (names or identifiers).
  • Inside the curly braces {}, you write the block’s body — parameters and arguments.

Example:

resource "aws_instance" "web_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode
  • resource is the block type

  • "aws_instance" and "web_server" are labels (resource type and resource name)

  • Inside {}, you define arguments (parameters to configure the resource)

2. Arguments

  • Arguments are key-value pairs inside a block that configure the block’s behavior.
  • The key is the argument name.
  • The value can be a string, number, boolean, list, map, or an expression.
  • Arguments define how a resource, provider, or variable is set up.

Example:

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"  # Argument
  instance_type = "t2.micro"                 # Argument
}
Enter fullscreen mode Exit fullscreen mode
  • These two lines are arguments specifying which Amazon Machine Image (AMI) to use and the instance size.

3. Parameters

Parameters are inputs that allow you to customize and reuse your Terraform configurations, especially within variables and modules.

  • Parameters define what values a block (like variable or module) expects from the user.
  • They make your configurations flexible by accepting dynamic input.
  • Parameters are declared inside blocks like variable or passed into module blocks.

Example:

variable "region" {
  description = "The AWS region where resources will be created"
  type        = string
  default     = "us-east-1"
}
Enter fullscreen mode Exit fullscreen mode
  • In this example, description, type, and default are parameters (arguments) that define the variable’s behavior.

Hands-On: Provisioning an S3 Bucket with Terraform

In this hands-on guide, we'll walk through the steps to create an Amazon S3 bucket using Terraform. This is perfect for beginners who want to get practical experience with Infrastructure as Code (IaC) on AWS.

Step 1: Verify Terraform and AWS CLI Versions

Before starting, make sure both Terraform and AWS CLI are installed and accessible in your terminal.

terraform -version
aws --version
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the AWS Provider Configuration

Create a file named provider.tf and configure the AWS provider. This tells Terraform which cloud and region to use.

#provider.tf
provider "aws" {
  region = "us-east-1"
}
Enter fullscreen mode Exit fullscreen mode
  • Make sure you’ve configured AWS CLI with your credentials using aws configure.

Step 3: Configure main.tf for S3 Bucket

  • Now create the main Terraform configuration to define the S3 bucket resource.
# main.tf
resource "aws_s3_bucket" "my_bucket" {
  bucket = "anand-ghangoria-bucket"  # Replace with a unique name

  tags = {
    Name        = "MyBucket"
    Environment = "Dev"
  }
}

Enter fullscreen mode Exit fullscreen mode
  • Bucket names must be globally unique across all AWS accounts. Modify bucket accordingly.

Step 4: Initialize, Plan, and Apply

  • Run the following Terraform commands in the terminal:
# Initialize the project (downloads provider plugins)
terraform init

# Preview the changes that will be made
terraform plan

# Apply the configuration to create the S3 bucket
terraform apply

Enter fullscreen mode Exit fullscreen mode
  • When prompted, type yes to confirm the apply step.

  • If everything was configured correctly, you should see an output like:

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Enter fullscreen mode Exit fullscreen mode

You’ve now successfully created an S3 bucket using Terraform!

STEP:5 Clean Up Resources

  • To delete the S3 bucket and avoid unwanted charges:
terraform destroy

Enter fullscreen mode Exit fullscreen mode

Hands-On: create an EC2 instance on AWS using Terraform

In this hands-on guide, we'll walk through the steps to create an Amazon EC2 instance using Terraform. This is perfect for beginners who want to get practical experience with Infrastructure as Code (IaC) on AWS.

Step 1: Verify Terraform and AWS CLI Versions

Before starting, make sure both Terraform and AWS CLI are installed and accessible in your terminal.

terraform -version
aws --version
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the AWS Provider Configuration

Create a file named provider.tf and configure the AWS provider. This tells Terraform which cloud and region to use.


# Configure the AWS Provider
provider "aws" {
  region = "us-east-1"
}
Enter fullscreen mode Exit fullscreen mode
  • Make sure you’ve configured AWS CLI with your credentials using aws configure.

Step 3: Configure main.tf for EC2 instance

  • Now create the main Terraform configuration to define the EC2 instance resource .
# main.tf
resource "aws_key_pair" "my_key" {
  key_name   = "delight"
  public_key = file("delight.pub")
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  key_name = aws_key_pair.my_key.key_name

  tags = {
    Name = "delight"
  }
}

Enter fullscreen mode Exit fullscreen mode

Step 4:Generate an SSH key pair named delight

ssh-keygen -t rsa -b 2048 -f delight
chmod 400 delight


Enter fullscreen mode Exit fullscreen mode
  • When prompted for a passphrase, you can just press Enter to skip it (or set one if you want).

Step 5: Initialize, Plan, and Apply

  • Run the following Terraform commands in the terminal:
# Initialize the project (downloads provider plugins)
terraform init

# Preview the changes that will be made
terraform plan

# Apply the configuration to create the S3 bucket
terraform apply

Enter fullscreen mode Exit fullscreen mode
  • When prompted, type yes to confirm the apply step.

  • If everything was configured correctly, you should see an output like:

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Enter fullscreen mode Exit fullscreen mode

You’ve now successfully created an ec2 instance using Terraform!

Step:6 Clean Up Resources

  • To delete the ec2 instace and avoid unwanted charges:
terraform destroy

Enter fullscreen mode Exit fullscreen mode

Terraform #IaC #FileStructure #DevOps #BestPractices #HashiCorp #CloudInfrastructure

Top comments (0)