🚀 DevOps Roadmap 2025 – Step 3: Mastering Terraform (Beginner to Pro Guide for Azure)

Learn how to automate and manage Azure infrastructure using Terraform — covering providers, variables, backend configuration, modules, state management, and 30+ essential commands with detailed interview questions for freshers and experienced engineers.
“Infrastructure as Code is the future of scalable, repeatable DevOps—and Terraform is at the heart of it.”
🛠 How to Install Terraform Locally and Connect to Azure
Before we start writing Terraform code, let’s set up your environment:
1. Install Terraform on Your Local Machine
Windows:
Download the latest Terraform zip from https://developer.hashicorp.com/terraform
Extract the zip file.
Move the
terraform.exe
to a folder, e.g.,C:\terraform\
.Add this folder to your system’s PATH environment variable:
Search “Environment Variables” in Windows Search.
Click Edit the system environment variables.
Under System Properties, click Environment Variables.
Select Path under System variables, click Edit, then New, and add
C:\terraform\
.Click OK and restart your terminal/PowerShell.
Verify installation by running:
terraform -version
Linux/macOS:
Use
wget
orcurl
to download, then unzip and move binary to/usr/local/bin
.Example:
wget https://releases.hashicorp.com/terraform/1.5.5/terraform_1.5.5_linux_amd64.zip unzip terraform_1.5.5_linux_amd64.zip sudo mv terraform /usr/local/bin/ terraform -version
2. Set Environment Variables for Azure Authentication
Terraform uses Azure credentials to provision resources. You have multiple authentication options:
Using Azure CL**I**
Install Azure CLI:
https://learn.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latestLogin:
az login
Terraform will automatically use this session for authentication.
Using Service Principal (Recommended for Automation**)**
Create Service Principal:
az ad sp create-for-rbac --name "TerraformSP" --role Contributor --scopes /subscriptions/<subscription-id>
Output will have:
appId
(Client ID)password
(Client Secret)tenant
Set environment variables:
export ARM_CLIENT_ID="<appId>" export ARM_CLIENT_SECRET="<password>" export ARM_SUBSCRIPTION_ID="<subscription-id>" export ARM_TENANT_ID="<tenant>"
For Windows PowerShell:
setx ARM_CLIENT_ID "<appId>" setx ARM_CLIENT_SECRET "<password>" setx ARM_SUBSCRIPTION_ID "<subscription-id>" setx ARM_TENANT_ID "<tenant>"
3. Verify Connection
To verify Terraform can connect to Azure, initialize Terraform in your working directory:
terraform init
Then plan your first deployment:
terraform plan
If authentication is successful, Terraform will be able to query your Azure subscription.
👨💻 What is Terraform?
Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp. It allows you to define your cloud infrastructure using simple configuration files and manage it in a version-controlled and automated way.
You can provision infrastructure in Azure, AWS, GCP, Kubernetes, and even SaaS platforms like GitHub and Datadog.
Instead of clicking manually in the Azure portal, you define infrastructure in code — fast, repeatable, and auditable.
🔧 Why Should DevOps Engineers Learn Terraform?
Here’s why every DevOps engineer, fresher or experienced, must know Terraform:
Automation: No more manual cloud setups
Consistency: Infra behaves the same across environments (dev, test, prod)
Version Control: Infra changes are tracked in Git
Reusability: Create modules once and use them everywhere
Multi-Cloud: Write once, run anywhere (Azure, AWS, GCP)
🧠 What Language Does Terraform Use?
Terraform uses HCL (HashiCorp Configuration Language) – a human-readable language that is declarative. This means you define what you want (a resource group in Azure), not how to create it.
Example:
resource "azurerm_resource_group" "example" {
name = "devops-rg"
location = "East US"
}
This simple code block provisions a resource group in Azure.
☁️ Terraform Providers in Azure
A provider is the plugin Terraform uses to interact with a platform like Azure.
For Azure, here are the most commonly used providers:
azurerm – For managing core Azure resources (VMs, RGs, storage, etc.)
azuread – For managing Azure Active Directory (users, groups)
azapi – For accessing new Azure features via REST API
random, null – Utility providers to generate random strings or create dummy resources
Each provider is declared like this:
provider "azurerm" {
features {}
}
🔢 Using Variables (Parameterization)
You can make your code dynamic by using variables.
Step 1: Define a variable
variable "location" {
type = string
default = "East US"
}
Step 2: Use the variable
resource "azurerm_resource_group" "example" {
name = "my-rg"
location = var.location
}
Step 3: Override it using .tfvars
or CLI
location = "West Europe"
Or:
terraform apply -var="location=Central India"
✅ This helps reuse your code for multiple environments.
🔁 Understanding Backend Configuration in Terraform
The state file (terraform.tfstate
) stores info about what’s already deployed.
By default, this file is stored locally. But in teams or CI/CD pipelines, it should be stored remotely, such as in an Azure Storage Account.
🛠 Example: Configure Remote Backend in Azure
terraform {
backend "azurerm" {
resource_group_name = "tfstate-rg"
storage_account_name = "tfstatestorage999"
container_name = "tfstate"
key = "dev.terraform.tfstate"
}
}
Before this works, create the storage manually:
az group create -n tfstate-rg -l eastus
az storage account create \
--name tfstatestorage999 \
--resource-group tfstate-rg \
--sku Standard_LRS
az storage container create \
--name tfstate \
--account-name tfstatestorage999
Then run:
terraform init
🔐 Why use backend?
Shared state
Locking
Recovery from crashes
Security (can integrate with Azure RBAC)
⛓️ Understanding depends_on
By default, Terraform figures out the order of resource creation. But when you want to force an order, use depends_on
.
resource "azurerm_resource_group" "rg" {
name = "mygroup"
location = "East US"
}
resource "azurerm_storage_account" "storage" {
name = "mystorage999"
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
account_tier = "Standard"
account_replication_type = "LRS"
depends_on = [azurerm_resource_group.rg]
}
✅ Use depends_on
when there's no direct reference but you still want Terraform to wait.
🧱 Using Modules in Terraform
Modules help you organize and reuse your Terraform code.
Example folder structure:
modules/
└── vnet/
├── main.tf
├── variables.tf
├── outputs.tf
main.tf
Using the module:
module "vnet" {
source = "./modules/vnet"
vnet_name = "devops-vnet"
location = "East US"
}
Benefits:
Cleaner code
Easier maintenance
Works great in large teams
💥 What Happens If the State File is Deleted?
If your .tfstate
file is deleted:
Terraform forgets what it deployed.
On
apply
, it will try to recreate everything.This can lead to duplicate resources or errors.
Fix Options:
Restore from backup
Import manually:
terraform import azurerm_resource_group.example /subscriptions/xxxx/resourceGroups/my-rg
- Use remote backend with versioning to avoid accidental deletion.
✅ Always enable blob versioning in Azure for .tfstate
.
✅ Real-World Azure Example
provider "azurerm" {
features {}
}
variable "location" {
default = "East US"
}
resource "azurerm_resource_group" "demo" {
name = "demo-rg"
location = var.location
}
Run:
terraform init
terraform plan
terraform apply
🔧 30+ Important Terraform Commands Every DevOps Engineer Should Know
Here is the list of essential Terraform commands you will use frequently:
Command | Description |
terraform init | Initialize Terraform working directory, downloads providers and sets up backend |
terraform plan | Creates an execution plan showing what will be created/updated/destroyed |
terraform apply | Applies the changes required to reach the desired state |
terraform destroy | Destroys the Terraform-managed infrastructure |
terraform fmt | Formats Terraform code files according to style conventions |
terraform validate | Validates the syntax of the configuration files |
terraform show | Shows details about the current state or plan |
terraform output | Shows the output variables from state file |
terraform import | Imports existing infrastructure into Terraform |
terraform taint <resource> | Marks a resource for recreation on next apply |
terraform untaint <resource> | Removes the taint mark from a resource |
terraform state list | Lists all resources tracked in the state file |
terraform state show <resource> | Shows detailed info about a resource in state |
terraform state rm <resource> | Removes a resource from state (without destroying it) |
terraform workspace list | Lists all Terraform workspaces (environments) |
terraform workspace new <name> | Creates a new workspace |
terraform workspace select <name> | Switches workspace |
terraform graph | Outputs the dependency graph in DOT format |
terraform providers | Lists provider dependencies |
terraform login | Logs into Terraform Cloud |
terraform logout | Logs out from Terraform Cloud |
terraform version | Shows Terraform version |
terraform force-unlock <ID> | Unlocks state if locked due to crashed operation |
terraform console | Interactive console to test expressions |
terraform apply -var 'key=value' | Override variable on CLI |
terraform plan -out=tfplan | Save plan to file |
terraform apply tfplan | Apply saved plan |
terraform refresh | Refresh state file with real infrastructure status |
terraform validate -json | Validate with JSON output for automation |
terraform providers mirror <dir> | Downloads all required providers into a local directory |
These commands help you manage your Terraform projects from initialization to complex state management.
❓ 20+ Common Terraform Interview Questions (Freshers + Experienced)
What is Terraform?
Terraform is an open-source Infrastructure as Code tool used to automate cloud infrastructure provisioning.What is the purpose of the
.tfstate
file?
It keeps track of the resources Terraform manages and their current state.What language does Terraform use?
Terraform uses HCL (HashiCorp Configuration Language), a declarative language.What is a provider in Terraform?
A provider is a plugin that allows Terraform to interact with cloud platforms like Azure, AWS, or GCP.What are modules in Terraform?
Modules are reusable packages of Terraform code to organize and manage infrastructure.How do you use variables in Terraform?
Variables make Terraform configurations dynamic and reusable.What is a backend in Terraform?
Backend defines where Terraform stores its state file (local or remote storage).What is
depends_on
used for?
It explicitly defines resource dependencies to control creation order.What happens if the state file is deleted?
Terraform loses track of resources and might try to recreate everything.How do you secure sensitive data in Terraform?
Use environment variables, Azure Key Vault, or encrypted secrets; never commit secrets to Git.Explain the difference between
terraform plan
andterraform apply
.plan
shows what changes will happen;apply
executes those changes.How can you import existing infrastructure into Terraform?
Using theterraform import
command.What is the use of workspaces in Terraform?
Workspaces allow managing multiple environments (like dev, prod) in a single configuration.What is the difference between
terraform taint
andterraform destroy
?taint
marks a resource for recreation on next apply;destroy
removes the resource completely.What command formats Terraform code?
terraform fmt
How do you handle secret values in Terraform variables?
Using sensitive variables and avoiding storing them in.tfvars
files that go into version control.What is remote state and why is it important?
Remote state stores.tfstate
file in a shared backend for collaboration and locking.How do you rollback changes if something goes wrong?
You can destroy resources or use Terraform state snapshots/backups.What is a provider version constraint?
It restricts Terraform to use a specific provider version to avoid breaking changes.What are the benefits of using modules?
Code reuse, consistency, easier maintenance.How to upgrade Terraform versions safely?
Check upgrade guides, runterraform plan
, and test in non-prod before upgrading production.Explain lifecycle blocks in Terraform?
Used to customize resource creation, prevent deletion, or control update behavior.What is interpolation in Terraform?
Injecting variable or resource values into configuration strings.How do you manage provider plugins?
Terraform downloads and manages providers duringterraform init
.What are outputs in Terraform?
Values that Terraform exports after apply for use elsewhere.
🧠 Best Practices
Use remote backend with locking
Always use
terraform plan
beforeapply
Format using
terraform fmt
Split infrastructure into modules
Use
.gitignore
to exclude sensitive filesUse versioned state storage (Azure Blob Versioning)
🐳 What’s Next?
In Step 4, we’ll learn Docker:
What is a container?
Docker vs Virtual Machine
Dockerfile hands-on
Docker Compose
CI/CD Integration with Docker
Docker Interview Questions
🙌 Final Words
If you're building a career in DevOps, SRE, or Cloud Engineering, Terraform is an essential skill. Whether you're a fresher writing your first .tf
file or an experienced engineer creating complex modules, this skill pays off—literally and technically.
Start with simple resources, build confidence, and move toward scalable, secure, and automated deployments.
Subscribe to my newsletter
Read articles from Harshal Sonar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
