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

Harshal SonarHarshal Sonar
10 min read

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:

    1. Download the latest Terraform zip from https://developer.hashicorp.com/terraform

    2. Extract the zip file.

    3. Move the terraform.exe to a folder, e.g., C:\terraform\.

    4. 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.

    5. Verify installation by running:

       terraform -version
      
  • Linux/macOS:

    Use wget or curl 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**

    1. Install Azure CLI:
      https://learn.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest

    2. Login:

       az login
      
    3. Terraform will automatically use this session for authentication.

  • Using Service Principal (Recommended for Automation**)**

    1. 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

    2. 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:

  1. azurerm – For managing core Azure resources (VMs, RGs, storage, etc.)

  2. azuread – For managing Azure Active Directory (users, groups)

  3. azapi – For accessing new Azure features via REST API

  4. 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:

  1. Restore from backup

  2. Import manually:

terraform import azurerm_resource_group.example /subscriptions/xxxx/resourceGroups/my-rg
  1. 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:

CommandDescription
terraform initInitialize Terraform working directory, downloads providers and sets up backend
terraform planCreates an execution plan showing what will be created/updated/destroyed
terraform applyApplies the changes required to reach the desired state
terraform destroyDestroys the Terraform-managed infrastructure
terraform fmtFormats Terraform code files according to style conventions
terraform validateValidates the syntax of the configuration files
terraform showShows details about the current state or plan
terraform outputShows the output variables from state file
terraform importImports 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 listLists 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 listLists all Terraform workspaces (environments)
terraform workspace new <name>Creates a new workspace
terraform workspace select <name>Switches workspace
terraform graphOutputs the dependency graph in DOT format
terraform providersLists provider dependencies
terraform loginLogs into Terraform Cloud
terraform logoutLogs out from Terraform Cloud
terraform versionShows Terraform version
terraform force-unlock <ID>Unlocks state if locked due to crashed operation
terraform consoleInteractive console to test expressions
terraform apply -var 'key=value'Override variable on CLI
terraform plan -out=tfplanSave plan to file
terraform apply tfplanApply saved plan
terraform refreshRefresh state file with real infrastructure status
terraform validate -jsonValidate 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)

  1. What is Terraform?
    Terraform is an open-source Infrastructure as Code tool used to automate cloud infrastructure provisioning.

  2. What is the purpose of the .tfstate file?
    It keeps track of the resources Terraform manages and their current state.

  3. What language does Terraform use?
    Terraform uses HCL (HashiCorp Configuration Language), a declarative language.

  4. What is a provider in Terraform?
    A provider is a plugin that allows Terraform to interact with cloud platforms like Azure, AWS, or GCP.

  5. What are modules in Terraform?
    Modules are reusable packages of Terraform code to organize and manage infrastructure.

  6. How do you use variables in Terraform?
    Variables make Terraform configurations dynamic and reusable.

  7. What is a backend in Terraform?
    Backend defines where Terraform stores its state file (local or remote storage).

  8. What is depends_on used for?
    It explicitly defines resource dependencies to control creation order.

  9. What happens if the state file is deleted?
    Terraform loses track of resources and might try to recreate everything.

  10. How do you secure sensitive data in Terraform?
    Use environment variables, Azure Key Vault, or encrypted secrets; never commit secrets to Git.

  11. Explain the difference between terraform plan and terraform apply.
    plan shows what changes will happen; apply executes those changes.

  12. How can you import existing infrastructure into Terraform?
    Using the terraform import command.

  13. What is the use of workspaces in Terraform?
    Workspaces allow managing multiple environments (like dev, prod) in a single configuration.

  14. What is the difference between terraform taint and terraform destroy?
    taint marks a resource for recreation on next apply; destroy removes the resource completely.

  15. What command formats Terraform code?
    terraform fmt

  16. How do you handle secret values in Terraform variables?
    Using sensitive variables and avoiding storing them in .tfvars files that go into version control.

  17. What is remote state and why is it important?
    Remote state stores .tfstate file in a shared backend for collaboration and locking.

  18. How do you rollback changes if something goes wrong?
    You can destroy resources or use Terraform state snapshots/backups.

  19. What is a provider version constraint?
    It restricts Terraform to use a specific provider version to avoid breaking changes.

  20. What are the benefits of using modules?
    Code reuse, consistency, easier maintenance.

  21. How to upgrade Terraform versions safely?
    Check upgrade guides, run terraform plan, and test in non-prod before upgrading production.

  22. Explain lifecycle blocks in Terraform?
    Used to customize resource creation, prevent deletion, or control update behavior.

  23. What is interpolation in Terraform?
    Injecting variable or resource values into configuration strings.

  24. How do you manage provider plugins?
    Terraform downloads and manages providers during terraform init.

  25. 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 before apply

  • Format using terraform fmt

  • Split infrastructure into modules

  • Use .gitignore to exclude sensitive files

  • Use 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.

0
Subscribe to my newsletter

Read articles from Harshal Sonar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harshal Sonar
Harshal Sonar