DEV Community

apikodes
apikodes

Posted on • Edited on

🚀 Terraform Basics: A Beginner's Guide to Infrastructure as Code (IaC)

This article offers a professional overview of Terraform, detailing its key features, workflow, and importance in contemporary DevOps practices. It covers typical use cases across different environments and addresses initial challenges to facilitate your adoption of Terraform. Let’s dive in.

🌱 What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp and written in GO language. It lets you define and provision cloud infrastructure using a simple, human-readable language called HCL (HashiCorp Configuration Language).

Whether you're working with AWS, Azure, GCP, or even Kubernetes, Terraform is the cloud-agnostic provisioning tool helps automate and manage resources consistently and safely.

🧠 Why Terraform?

✅ Cloud-Agnostic — Works across cloud providers
✅ Declarative Syntax — Describe what you want, not how
✅ Version Control Friendly — Code lives in Git
✅ Reusable Modules — Create DRY infrastructure
✅ State Management — Tracks infrastructure changes over time

🔧 Install Terraform

brew tap hashicorp/tap
brew install hashicorp/tap/terraform
Enter fullscreen mode Exit fullscreen mode
  • Windows (with Chocolatey):
choco install terraform
Enter fullscreen mode Exit fullscreen mode
  • Linux
sudo apt-get update && sudo apt-get install terraform
Enter fullscreen mode Exit fullscreen mode
  • AWS CloudShell
sudo yum install -y tree yum-utils && sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo && sudo yum -y install terraform
Enter fullscreen mode Exit fullscreen mode
  • Check version:
# Linux
terraform -v
Terraform v1.11.3
on linux_amd64

# Windows
terraform -v
Terraform v1.11.3
on windows_amd64
Enter fullscreen mode Exit fullscreen mode

🧠 Key Terraform components

Terraform keeps track of your infrastructure's state by comparing your current setup (defined in code) with a file it creates after running.

Providers

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

  • AWS
provider "aws" { region = "us-east-1" }
Enter fullscreen mode Exit fullscreen mode
  • Azure
provider "azurerm" {
  subscription_id = ""
  resource_provider_registrations = "none"
}
Enter fullscreen mode Exit fullscreen mode

Resources

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

resource "aws_vpc" "tf_vpc" { ... }
resource "aws_instance" "tf_web" { ... }
resource "aws_s3_bucket" "tf_s3_data" { ... }
Enter fullscreen mode Exit fullscreen mode

Variables

Allow you to customize configurations without changing the code.

variable "vpc_cidr" { default = "172.31.0.0/16" }
variable "instance_type" { default = "t2.micro" }
variable "bucket_name" { default = "tfs3bucketdata" }
Enter fullscreen mode Exit fullscreen mode

Outputs

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

output "instance_ip" { value = aws_instance.tf_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 or Terraform Cloud).

🔁 Terraform Lifecycle Workflow

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

  • 1. Initialize
# Init – Run terraform init to initialize the working directory and download providers.

terraform init
Enter fullscreen mode Exit fullscreen mode
  • 2. Plan
# Plan – Preview changes with before making any updates.
terraform plan
Enter fullscreen mode Exit fullscreen mode
  • 3. Apply
# Apply – Execute changes to provision or update resources.
terraform apply
Enter fullscreen mode Exit fullscreen mode
  • 4. Destroy
# Destroys all resources defined in your Terraform configuration.
terraform destroy
Enter fullscreen mode Exit fullscreen mode

🔍 Terraform Files 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.

🔁 Hashicrop Configuration Language (HCL)

What is HCL?

  • HCL (HashiCorp Configuration Language) is a declarative language created by HashiCorp.
  • Primarily used in tools like Terraform for defining Infrastructure as Code (IaC).
  • Human-friendly: Simple to write and comprehend.
  • Declarative: Specifies desired outcomes, not procedural steps.
  • Machine-optimized: Easily parsed and processed by software.
  • HCL enables clear, structured management and provisioning of cloud resources (e.g., AWS, Azure, GCP).

HCL Syntax: Blocks, Parameters, and Arguments

1. Blocks

  • Blocks serve as the core building blocks in HCL, organizing configuration settings.
  • A block begins with a block type (e.g., resource, provider, variable, module).
  • A block includes one or more labels (names or identifiers).
  • The block’s body, enclosed in curly braces {}, contains parameters and arguments.
Block Example

resource "aws_vpc" "terraform_vpc" {
  cidr_block         = "172.31.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "terraform_vpc"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • resource is the block type
  • aws_instance and web_server are labels (resource type and resource name)
  • aws_vpc and terraform_vpc are labels (resource type and resource name)
  • Inside {}, you define arguments (parameters to configure the resource)

2. Arguments

  • Arguments are key-value pairs within a block that define its behavior.
  • The key represents the argument name.
  • The value can be a string, number, boolean, list, map, or an expression.
  • Arguments specify the configuration for resources, providers, or variables.
Argument Example

resource "aws_vpc" "terraform_vpc" {
  cidr_block         = "172.31.0.0/16" # Argument
  enable_dns_hostnames = true          # Argument
  enable_dns_support   = true          # Argument

  tags = {
    Name = "terraform_vpc"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • The above lines are arguments specifying details about VPC Configurations like CIDR Block and DNS Settings.

3. Parameters

  • Parameters are inputs that enable customization and reusability in Terraform configurations, particularly for variables and modules.

  • Parameters define what values a block (like variable or module) expects from the user.

  • Parameters enhance flexibility by allowing dynamic input.

  • Parameters are defined within blocks like variable or passed into module blocks.

Parameters Example
variable "vpc_cidr" {
  description = "Enter the VPC CIDR Value."
  type    = string
  default = "172.31.0.0/16"
}
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 practical guide, we'll go through the process of creating an Amazon S3 bucket with Terraform, ideal for beginners looking to gain hands-on experience with Infrastructure as Code (IaC) on AWS.

Step 1: Verify Terraform and AWS CLI Versions

  • Ensure that Terraform and the AWS CLI are installed and available in your terminal before beginning.
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 Resource

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

  tags = {
    Name        = "TFMyBucket"
    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: Provisioning an EC2 instance on AWS using Terraform

  • In this practical guide, we'll go through the process of creating an Amazon EC2 instance with Terraform, ideal for beginners seeking hands-on experience with Infrastructure as Code (IaC) on AWS.

Step 1: Verify Terraform and AWS CLI Versions

  • Ensure that Terraform and the AWS CLI are installed and available in your terminal before beginning.
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 variables.tf for Resource Parameters

# variables.tf
variable "instance_type" {
  description = "Enter the EC2 Instance Type"
  type    = string
  default = "t2.micro"
}

variable "vol_size" {
  description = "Enter the EC2 Instance Volume Size"
  type    = number
  default = 8
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure main.tf for EC2 instance Resource

  • Now create the main Terraform configuration to define the EC2 instance resource
# main.tf
resource "aws_key_pair" "tf_key" {
  key_name   = "tfec2"
  public_key = file("tfec2.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 = var.instance_type
  key_name      = aws_key_pair.tf_key.key_name

  root_block_device {
    volume_size = var.vol_size
  }

  tags = {
    Name = "tf_ec2_instance"
  }

}
Enter fullscreen mode Exit fullscreen mode

Step 5: Generate an SSH key pair named tfec2

ssh-keygen -t rsa -b 2048 -f tfec2
chmod 400 tfec2
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 6: 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 EC2 Instance
terraform apply
Enter fullscreen mode Exit fullscreen mode

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

Terraform stores information about your infrastructure in a state file.
Terraform apply will also write data to the terraform .tfstate file.
This state file keeps track of resources created by your configuration and maps them to real-world resources.

Step 7: Clean Up Resources

  • To delete the ec2 instace and avoid unwanted charges:
terraform destroy
Enter fullscreen mode Exit fullscreen mode

Top comments (0)